Skip to content

Commit

Permalink
refactor: setup and apply Prettier (#463)
Browse files Browse the repository at this point in the history
  • Loading branch information
G-Rath authored Apr 7, 2024
1 parent d864d5a commit ce75a9c
Show file tree
Hide file tree
Showing 55 changed files with 582 additions and 537 deletions.
14 changes: 6 additions & 8 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
module.exports = {
extends: ['airbnb', 'prettier'],
extends: ["airbnb", "plugin:prettier/recommended"],
rules: {
'comma-dangle': ['error', 'never'],
'import/no-unresolved': 'off',
'import/no-extraneous-dependencies': 'off',
'import/extensions': 'off',
"indent": ["error", 2],
semi: ['error', 'never']
"import/no-unresolved": "off",
"import/no-extraneous-dependencies": "off",
"import/extensions": "off",
indent: ["error", 2]
},
env: {
browser: true,
Expand All @@ -18,7 +16,7 @@ module.exports = {
// todo: these should be sourced from eslint-plugin-jest
env: { jest: true },
rules: {
'global-require': 'off'
"global-require": "off"
}
}
]
Expand Down
5 changes: 1 addition & 4 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
module.exports = {
roots: ["<rootDir>/test"],
testPathIgnorePatterns: [
"/__fixtures__/",
"/__utils__/"
]
testPathIgnorePatterns: ["/__fixtures__/", "/__utils__/"]
}
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,12 @@
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-import": "^2.24.2",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-react": "^7.26.0",
"eslint-plugin-react-hooks": "^4.6.0",
"jest": "^28.1.3",
"memory-fs": "^0.5.0",
"prettier": "^3.2.5",
"swc-loader": "^0.1.15",
"thenify": "^3.3.1",
"webpack": "^5.72.0",
Expand Down
30 changes: 15 additions & 15 deletions package/babel/preset.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
const { moduleExists } = require('shakapacker')
const { moduleExists } = require("shakapacker")

module.exports = function config(api) {
const validEnv = ['development', 'test', 'production']
const validEnv = ["development", "test", "production"]
const currentEnv = api.env()
const isDevelopmentEnv = api.env('development')
const isProductionEnv = api.env('production')
const isTestEnv = api.env('test')
const isDevelopmentEnv = api.env("development")
const isProductionEnv = api.env("production")
const isTestEnv = api.env("test")

if (!validEnv.includes(currentEnv)) {
throw new Error(
Expand All @@ -17,21 +17,21 @@ module.exports = function config(api) {

return {
presets: [
isTestEnv && ['@babel/preset-env', { targets: { node: 'current' } }],
isTestEnv && ["@babel/preset-env", { targets: { node: "current" } }],
(isProductionEnv || isDevelopmentEnv) && [
'@babel/preset-env',
"@babel/preset-env",
{
useBuiltIns: 'entry',
corejs: '3.8',
modules: 'auto',
useBuiltIns: "entry",
corejs: "3.8",
modules: "auto",
bugfixes: true,
exclude: ['transform-typeof-symbol']
exclude: ["transform-typeof-symbol"]
}
],
moduleExists('@babel/preset-typescript') && '@babel/preset-typescript'
moduleExists("@babel/preset-typescript") && "@babel/preset-typescript"
].filter(Boolean),
plugins: [
['@babel/plugin-transform-runtime', { helpers: false }]
].filter(Boolean)
plugins: [["@babel/plugin-transform-runtime", { helpers: false }]].filter(
Boolean
)
}
}
28 changes: 15 additions & 13 deletions package/config.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,31 @@
const { resolve } = require('path')
const { load } = require('js-yaml')
const { existsSync, readFileSync } = require('fs')
const { resolve } = require("path")
const { load } = require("js-yaml")
const { existsSync, readFileSync } = require("fs")

const { merge } = require('webpack-merge')
const { ensureTrailingSlash } = require('./utils/helpers')
const { railsEnv } = require('./env')
const configPath = require('./utils/configPath')
const { merge } = require("webpack-merge")
const { ensureTrailingSlash } = require("./utils/helpers")
const { railsEnv } = require("./env")
const configPath = require("./utils/configPath")

const defaultConfigPath = require('./utils/defaultConfigPath')
const defaultConfigPath = require("./utils/defaultConfigPath")

const getDefaultConfig = () => {
const defaultConfig = load(readFileSync(defaultConfigPath), 'utf8')
const defaultConfig = load(readFileSync(defaultConfigPath), "utf8")
return defaultConfig[railsEnv] || defaultConfig.production
}

const defaults = getDefaultConfig()
let config

if (existsSync(configPath)) {
const appYmlObject = load(readFileSync(configPath), 'utf8')
const appYmlObject = load(readFileSync(configPath), "utf8")
const envAppConfig = appYmlObject[railsEnv]

if (!envAppConfig) {
/* eslint no-console:0 */
console.warn(`Warning: ${railsEnv} key not found in the configuration file. Using production configuration as a fallback.`)
console.warn(
`Warning: ${railsEnv} key not found in the configuration file. Using production configuration as a fallback.`
)
}

config = merge(defaults, envAppConfig || {})
Expand All @@ -36,7 +38,7 @@ config.outputPath = resolve(config.public_root_path, config.public_output_path)
// Ensure that the publicPath includes our asset host so dynamic imports
// (code-splitting chunks and static assets) load from the CDN instead of a relative path.
const getPublicPath = () => {
const rootUrl = ensureTrailingSlash(process.env.SHAKAPACKER_ASSET_HOST || '/')
const rootUrl = ensureTrailingSlash(process.env.SHAKAPACKER_ASSET_HOST || "/")
return `${rootUrl}${config.public_output_path}/`
}

Expand All @@ -46,7 +48,7 @@ config.publicPathWithoutCDN = `/${config.public_output_path}/`
if (config.manifest_path) {
config.manifestPath = resolve(config.manifest_path)
} else {
config.manifestPath = resolve(config.outputPath, 'manifest.json')
config.manifestPath = resolve(config.outputPath, "manifest.json")
}

module.exports = config
6 changes: 3 additions & 3 deletions package/dev_server.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// These are the raw shakapacker dev server config settings from the YML file with ENV overrides applied.
const { isBoolean } = require('./utils/helpers')
const config = require('./config')
const { isBoolean } = require("./utils/helpers")
const config = require("./config")

const envFetch = (key) => {
const value = process.env[key]
Expand All @@ -10,7 +10,7 @@ const envFetch = (key) => {
const devServerConfig = config.dev_server

if (devServerConfig) {
const envPrefix = config.dev_server.env_prefix || 'SHAKAPACKER_DEV_SERVER'
const envPrefix = config.dev_server.env_prefix || "SHAKAPACKER_DEV_SERVER"

Object.keys(devServerConfig).forEach((key) => {
const envValue = envFetch(`${envPrefix}_${key.toUpperCase()}`)
Expand Down
36 changes: 19 additions & 17 deletions package/env.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,42 @@
const { load } = require('js-yaml')
const { readFileSync } = require('fs')
const defaultConfigPath = require('./utils/defaultConfigPath')
const { load } = require("js-yaml")
const { readFileSync } = require("fs")
const defaultConfigPath = require("./utils/defaultConfigPath")

const NODE_ENVIRONMENTS = ['development', 'production', 'test']
const DEFAULT = 'production'
const configPath = require('./utils/configPath')
const NODE_ENVIRONMENTS = ["development", "production", "test"]
const DEFAULT = "production"
const configPath = require("./utils/configPath")

const railsEnv = process.env.RAILS_ENV
const rawNodeEnv = process.env.NODE_ENV
const nodeEnv
= rawNodeEnv && NODE_ENVIRONMENTS.includes(rawNodeEnv) ? rawNodeEnv : DEFAULT
const isProduction = nodeEnv === 'production'
const isDevelopment = nodeEnv === 'development'
const nodeEnv =
rawNodeEnv && NODE_ENVIRONMENTS.includes(rawNodeEnv) ? rawNodeEnv : DEFAULT
const isProduction = nodeEnv === "production"
const isDevelopment = nodeEnv === "development"

let config
try {
config = load(readFileSync(configPath), 'utf8')
config = load(readFileSync(configPath), "utf8")
} catch (error) {
if (error.code === 'ENOENT') {
if (error.code === "ENOENT") {
// File not found, use default configuration
config = load(readFileSync(defaultConfigPath), 'utf8')
config = load(readFileSync(defaultConfigPath), "utf8")
} else {
throw error
}
}

const availableEnvironments = Object.keys(config).join('|')
const regex = new RegExp(`^(${availableEnvironments})$`, 'g')
const availableEnvironments = Object.keys(config).join("|")
const regex = new RegExp(`^(${availableEnvironments})$`, "g")

const runningWebpackDevServer = process.env.WEBPACK_SERVE === 'true'
const runningWebpackDevServer = process.env.WEBPACK_SERVE === "true"

const validatedRailsEnv = railsEnv && railsEnv.match(regex) ? railsEnv : DEFAULT

if (railsEnv && validatedRailsEnv !== railsEnv) {
/* eslint no-console:0 */
console.warn(`Warning: '${railsEnv}' environment not found in the configuration. Using '${DEFAULT}' configuration as a fallback.`)
console.warn(
`Warning: '${railsEnv}' environment not found in the configuration. Using '${DEFAULT}' configuration as a fallback.`
)
}

module.exports = {
Expand Down
44 changes: 22 additions & 22 deletions package/environments/base.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
/* eslint global-require: 0 */
/* eslint import/no-dynamic-require: 0 */

const { existsSync, readdirSync } = require('fs')
const { basename, dirname, join, relative, resolve } = require('path')
const extname = require('path-complete-extname')
const WebpackAssetsManifest = require('webpack-assets-manifest')
const webpack = require('webpack')
const rules = require('../rules')
const config = require('../config')
const { isProduction } = require('../env')
const { moduleExists } = require('../utils/helpers')
const { existsSync, readdirSync } = require("fs")
const { basename, dirname, join, relative, resolve } = require("path")
const extname = require("path-complete-extname")
const WebpackAssetsManifest = require("webpack-assets-manifest")
const webpack = require("webpack")
const rules = require("../rules")
const config = require("../config")
const { isProduction } = require("../env")
const { moduleExists } = require("../utils/helpers")

const getFilesInDirectory = (dir, includeNested) => {
if (!existsSync(dir)) {
Expand All @@ -32,10 +32,10 @@ const getFilesInDirectory = (dir, includeNested) => {
const getEntryObject = () => {
const entries = {}
const rootPath = join(config.source_path, config.source_entry_path)
if (config.source_entry_path === '/' && config.nested_entries) {
if (config.source_entry_path === "/" && config.nested_entries) {
throw new Error(
"Your shakapacker config specified using a source_entry_path of '/' with 'nested_entries' == " +
"'true'. Doing this would result in packs for every one of your source files"
"'true'. Doing this would result in packs for every one of your source files"
)
}

Expand Down Expand Up @@ -67,7 +67,7 @@ const getModulePaths = () => {
if (config.additional_paths) {
config.additional_paths.forEach((path) => result.push(resolve(path)))
}
result.push('node_modules')
result.push("node_modules")

return result
}
Expand All @@ -84,9 +84,9 @@ const getPlugins = () => {
})
]

if (moduleExists('css-loader') && moduleExists('mini-css-extract-plugin')) {
const hash = isProduction || config.useContentHash ? '-[contenthash:8]' : ''
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
if (moduleExists("css-loader") && moduleExists("mini-css-extract-plugin")) {
const hash = isProduction || config.useContentHash ? "-[contenthash:8]" : ""
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
plugins.push(
new MiniCssExtractPlugin({
filename: `css/[name]${hash}.css`,
Expand All @@ -104,35 +104,35 @@ const getPlugins = () => {

// Don't use contentHash except for production for performance
// https://webpack.js.org/guides/build-performance/#avoid-production-specific-tooling
const hash = isProduction || config.useContentHash ? '-[contenthash]' : ''
const hash = isProduction || config.useContentHash ? "-[contenthash]" : ""

module.exports = {
mode: 'production',
mode: "production",
output: {
filename: `js/[name]${hash}.js`,
chunkFilename: `js/[name]${hash}.chunk.js`,

// https://webpack.js.org/configuration/output/#outputhotupdatechunkfilename
hotUpdateChunkFilename: 'js/[id].[fullhash].hot-update.js',
hotUpdateChunkFilename: "js/[id].[fullhash].hot-update.js",
path: config.outputPath,
publicPath: config.publicPath
},
entry: getEntryObject(),
resolve: {
extensions: ['.js', '.jsx', '.mjs', '.ts', '.tsx', '.coffee'],
extensions: [".js", ".jsx", ".mjs", ".ts", ".tsx", ".coffee"],
modules: getModulePaths()
},

plugins: getPlugins(),

resolveLoader: {
modules: ['node_modules']
modules: ["node_modules"]
},

optimization: {
splitChunks: { chunks: 'all' },
splitChunks: { chunks: "all" },

runtimeChunk: 'single'
runtimeChunk: "single"
},

module: {
Expand Down
12 changes: 6 additions & 6 deletions package/environments/development.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
const { merge } = require('webpack-merge')
const { merge } = require("webpack-merge")

const baseConfig = require('./base')
const webpackDevServerConfig = require('../webpackDevServerConfig')
const { runningWebpackDevServer } = require('../env')
const baseConfig = require("./base")
const webpackDevServerConfig = require("../webpackDevServerConfig")
const { runningWebpackDevServer } = require("../env")

const devConfig = {
mode: 'development',
devtool: 'cheap-module-source-map',
mode: "development",
devtool: "cheap-module-source-map",
...(runningWebpackDevServer && { devServer: webpackDevServerConfig() })
}

Expand Down
Loading

0 comments on commit ce75a9c

Please sign in to comment.