Browse Source

FIX | Change webpack config to prevent fail on build

merge-requests/254/head
Oksana Stepanenko 2 years ago
parent
commit
3696c9c831
  1. 403
      config/webpack.config.js

403
config/webpack.config.js

@ -82,7 +82,7 @@ const hasJsxRuntime = (() => {
// This is the production and development configuration. // This is the production and development configuration.
// It is focused on developer experience, fast rebuilds, and a minimal bundle. // It is focused on developer experience, fast rebuilds, and a minimal bundle.
module.exports = function(webpackEnv) { module.exports = function (webpackEnv) {
const isEnvDevelopment = webpackEnv === "development"; const isEnvDevelopment = webpackEnv === "development";
const isEnvProduction = webpackEnv === "production"; const isEnvProduction = webpackEnv === "production";
@ -107,9 +107,11 @@ module.exports = function(webpackEnv) {
loader: MiniCssExtractPlugin.loader, loader: MiniCssExtractPlugin.loader,
// css is located in `static/css`, use '../../' to locate index.html folder // css is located in `static/css`, use '../../' to locate index.html folder
// in production `paths.publicUrlOrPath` can be a relative path // in production `paths.publicUrlOrPath` can be a relative path
options: paths.publicUrlOrPath.startsWith(".") options: paths.publicUrlOrPath.startsWith(".") ?
? { publicPath: "../../" } {
: {}, publicPath: "../../"
} :
{},
}, },
{ {
loader: require.resolve("css-loader"), loader: require.resolve("css-loader"),
@ -142,21 +144,18 @@ module.exports = function(webpackEnv) {
}, },
].filter(Boolean); ].filter(Boolean);
if (preProcessor) { if (preProcessor) {
loaders.push( loaders.push({
{ loader: require.resolve("resolve-url-loader"),
loader: require.resolve("resolve-url-loader"), options: {
options: { sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, root: paths.appSrc,
root: paths.appSrc,
},
}, },
{ }, {
loader: require.resolve(preProcessor), loader: require.resolve(preProcessor),
options: { options: {
sourceMap: true, sourceMap: true,
}, },
} });
);
} }
return loaders; return loaders;
}; };
@ -165,38 +164,37 @@ module.exports = function(webpackEnv) {
mode: isEnvProduction ? "production" : isEnvDevelopment && "development", mode: isEnvProduction ? "production" : isEnvDevelopment && "development",
// Stop compilation early in production // Stop compilation early in production
bail: isEnvProduction, bail: isEnvProduction,
devtool: isEnvProduction devtool: isEnvProduction ?
? shouldUseSourceMap shouldUseSourceMap ?
? "source-map" "source-map" :
: false false :
: isEnvDevelopment && "cheap-module-source-map", isEnvDevelopment && "cheap-module-source-map",
// These are the "entry points" to our application. // These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle. // This means they will be the "root" imports that are included in JS bundle.
entry: entry: isEnvDevelopment && !shouldUseReactRefresh ?
isEnvDevelopment && !shouldUseReactRefresh [
? [ // Include an alternative client for WebpackDevServer. A client's job is to
// Include an alternative client for WebpackDevServer. A client's job is to // connect to WebpackDevServer by a socket and get notified about changes.
// connect to WebpackDevServer by a socket and get notified about changes. // When you save a file, the client will either apply hot updates (in case
// When you save a file, the client will either apply hot updates (in case // of CSS changes), or refresh the page (in case of JS changes). When you
// of CSS changes), or refresh the page (in case of JS changes). When you // make a syntax error, this client will display a syntax error overlay.
// make a syntax error, this client will display a syntax error overlay. // Note: instead of the default WebpackDevServer client, we use a custom one
// Note: instead of the default WebpackDevServer client, we use a custom one // to bring better experience for Create React App users. You can replace
// to bring better experience for Create React App users. You can replace // the line below with these two lines if you prefer the stock client:
// the line below with these two lines if you prefer the stock client: //
// // require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack-dev-server/client') + '?/', // require.resolve('webpack/hot/dev-server'),
// require.resolve('webpack/hot/dev-server'), //
// // When using the experimental react-refresh integration,
// When using the experimental react-refresh integration, // the webpack plugin takes care of injecting the dev client for us.
// the webpack plugin takes care of injecting the dev client for us. webpackDevClientEntry,
webpackDevClientEntry, // Finally, this is your app's code:
// Finally, this is your app's code: paths.appIndexJs,
paths.appIndexJs, // We include the app code last so that if there is a runtime error during
// We include the app code last so that if there is a runtime error during // initialization, it doesn't blow up the WebpackDevServer client, and
// initialization, it doesn't blow up the WebpackDevServer client, and // changing JS code would still trigger a refresh.
// changing JS code would still trigger a refresh. ] :
] paths.appIndexJs,
: paths.appIndexJs,
output: { output: {
// The build folder. // The build folder.
path: isEnvProduction ? paths.appBuild : undefined, path: isEnvProduction ? paths.appBuild : undefined,
@ -204,28 +202,28 @@ module.exports = function(webpackEnv) {
pathinfo: isEnvDevelopment, pathinfo: isEnvDevelopment,
// There will be one main bundle, and one file per asynchronous chunk. // There will be one main bundle, and one file per asynchronous chunk.
// In development, it does not produce real files. // In development, it does not produce real files.
filename: isEnvProduction filename: isEnvProduction ?
? "static/js/[name].[contenthash:8].js" "static/js/[name].[contenthash:8].js" :
: isEnvDevelopment && "static/js/bundle.js", isEnvDevelopment && "static/js/bundle.js",
// TODO: remove this when upgrading to webpack 5 // TODO: remove this when upgrading to webpack 5
futureEmitAssets: true, futureEmitAssets: true,
// There are also additional JS chunk files if you use code splitting. // There are also additional JS chunk files if you use code splitting.
chunkFilename: isEnvProduction chunkFilename: isEnvProduction ?
? "static/js/[name].[contenthash:8].chunk.js" "static/js/[name].[contenthash:8].chunk.js" :
: isEnvDevelopment && "static/js/[name].chunk.js", isEnvDevelopment && "static/js/[name].chunk.js",
// webpack uses `publicPath` to determine where the app is being served from. // webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path. // It requires a trailing slash, or the file assets will get an incorrect path.
// We inferred the "public path" (such as / or /my-project) from homepage. // We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: paths.publicUrlOrPath, publicPath: paths.publicUrlOrPath,
// Point sourcemap entries to original disk location (format as URL on Windows) // Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: isEnvProduction devtoolModuleFilenameTemplate: isEnvProduction ?
? (info) => (info) =>
path path
.relative(paths.appSrc, info.absoluteResourcePath) .relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, "/") .replace(/\\/g, "/") :
: isEnvDevelopment && isEnvDevelopment &&
((info) => ((info) =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, "/")), path.resolve(info.absoluteResourcePath).replace(/\\/g, "/")),
// Prevents conflicts when multiple webpack runtimes (from different apps) // Prevents conflicts when multiple webpack runtimes (from different apps)
// are used on the same page. // are used on the same page.
jsonpFunction: `webpackJsonp${appPackageJson.name}`, jsonpFunction: `webpackJsonp${appPackageJson.name}`,
@ -281,19 +279,23 @@ module.exports = function(webpackEnv) {
new OptimizeCSSAssetsPlugin({ new OptimizeCSSAssetsPlugin({
cssProcessorOptions: { cssProcessorOptions: {
parser: safePostCssParser, parser: safePostCssParser,
map: shouldUseSourceMap map: shouldUseSourceMap ?
? { {
// `inline: false` forces the sourcemap to be output into a // `inline: false` forces the sourcemap to be output into a
// separate file // separate file
inline: false, inline: false,
// `annotation: true` appends the sourceMappingURL to the end of // `annotation: true` appends the sourceMappingURL to the end of
// the css file, helping the browser find the sourcemap // the css file, helping the browser find the sourcemap
annotation: true, annotation: true,
} } :
: false, false,
}, },
cssProcessorPluginOptions: { cssProcessorPluginOptions: {
preset: ["default", { minifyFontValues: { removeQuotes: false } }], preset: ["default", {
minifyFontValues: {
removeQuotes: false
}
}],
}, },
}), }),
], ],
@ -365,18 +367,16 @@ module.exports = function(webpackEnv) {
strictExportPresence: true, strictExportPresence: true,
rules: [ rules: [
// Disable require.ensure as it's not a standard language feature. // Disable require.ensure as it's not a standard language feature.
{ parser: { requireEnsure: false } }, {
parser: {
requireEnsure: false
}
},
{ {
include: /node_modules/, include: /node_modules/,
test: /\.mjs$/, test: /\.mjs$/,
type: "javascript/auto", type: "javascript/auto",
}, },
{
test: /\.js$/,
// exclude: /node_modules/, // This is the line that caused the problem. Remove or comment it out.
enforce: "pre",
use: ["source-map-loader"],
},
{ {
// "oneOf" will traverse all following loaders until one will // "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall // match the requirements. When no loader matches it will fall
@ -434,8 +434,7 @@ module.exports = function(webpackEnv) {
{ {
loaderMap: { loaderMap: {
svg: { svg: {
ReactComponent: ReactComponent: "@svgr/webpack?-svgo,+titleProp,+ref![path]",
"@svgr/webpack?-svgo,+titleProp,+ref![path]",
}, },
}, },
}, },
@ -456,8 +455,8 @@ module.exports = function(webpackEnv) {
}, },
], ],
isEnvDevelopment && isEnvDevelopment &&
shouldUseReactRefresh && shouldUseReactRefresh &&
require.resolve("react-refresh/babel"), require.resolve("react-refresh/babel"),
].filter(Boolean), ].filter(Boolean),
// This is a feature of `babel-loader` for webpack (not Babel itself). // This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/ // It enables caching results in ./node_modules/.cache/babel-loader/
@ -481,7 +480,9 @@ module.exports = function(webpackEnv) {
presets: [ presets: [
[ [
require.resolve("babel-preset-react-app/dependencies"), require.resolve("babel-preset-react-app/dependencies"),
{ helpers: true }, {
helpers: true
},
], ],
], ],
cacheDirectory: true, cacheDirectory: true,
@ -507,9 +508,9 @@ module.exports = function(webpackEnv) {
exclude: cssModuleRegex, exclude: cssModuleRegex,
use: getStyleLoaders({ use: getStyleLoaders({
importLoaders: 1, importLoaders: 1,
sourceMap: isEnvProduction sourceMap: isEnvProduction ?
? shouldUseSourceMap shouldUseSourceMap :
: isEnvDevelopment, isEnvDevelopment,
}), }),
// Don't consider CSS imports dead code even if the // Don't consider CSS imports dead code even if the
// containing package claims to have no side effects. // containing package claims to have no side effects.
@ -523,9 +524,9 @@ module.exports = function(webpackEnv) {
test: cssModuleRegex, test: cssModuleRegex,
use: getStyleLoaders({ use: getStyleLoaders({
importLoaders: 1, importLoaders: 1,
sourceMap: isEnvProduction sourceMap: isEnvProduction ?
? shouldUseSourceMap shouldUseSourceMap :
: isEnvDevelopment, isEnvDevelopment,
modules: { modules: {
getLocalIdent: getCSSModuleLocalIdent, getLocalIdent: getCSSModuleLocalIdent,
}, },
@ -537,12 +538,11 @@ module.exports = function(webpackEnv) {
{ {
test: sassRegex, test: sassRegex,
exclude: sassModuleRegex, exclude: sassModuleRegex,
use: getStyleLoaders( use: getStyleLoaders({
{
importLoaders: 3, importLoaders: 3,
sourceMap: isEnvProduction sourceMap: isEnvProduction ?
? shouldUseSourceMap shouldUseSourceMap :
: isEnvDevelopment, isEnvDevelopment,
}, },
"sass-loader" "sass-loader"
), ),
@ -556,12 +556,11 @@ module.exports = function(webpackEnv) {
// using the extension .module.scss or .module.sass // using the extension .module.scss or .module.sass
{ {
test: sassModuleRegex, test: sassModuleRegex,
use: getStyleLoaders( use: getStyleLoaders({
{
importLoaders: 3, importLoaders: 3,
sourceMap: isEnvProduction sourceMap: isEnvProduction ?
? shouldUseSourceMap shouldUseSourceMap :
: isEnvDevelopment, isEnvDevelopment,
modules: { modules: {
getLocalIdent: getCSSModuleLocalIdent, getLocalIdent: getCSSModuleLocalIdent,
}, },
@ -595,36 +594,34 @@ module.exports = function(webpackEnv) {
new Dotenv(), new Dotenv(),
// Generates an `index.html` file with the <script> injected. // Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin( new HtmlWebpackPlugin(
Object.assign( Object.assign({}, {
{},
{
inject: true, inject: true,
template: paths.appHtml, template: paths.appHtml,
}, },
isEnvProduction isEnvProduction ?
? { {
minify: { minify: {
removeComments: true, removeComments: true,
collapseWhitespace: true, collapseWhitespace: true,
removeRedundantAttributes: true, removeRedundantAttributes: true,
useShortDoctype: true, useShortDoctype: true,
removeEmptyAttributes: true, removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true, removeStyleLinkTypeAttributes: true,
keepClosingSlash: true, keepClosingSlash: true,
minifyJS: true, minifyJS: true,
minifyCSS: true, minifyCSS: true,
minifyURLs: true, minifyURLs: true,
}, },
} } :
: undefined undefined
) )
), ),
// Inlines the webpack runtime script. This script is too small to warrant // Inlines the webpack runtime script. This script is too small to warrant
// a network request. // a network request.
// https://github.com/facebook/create-react-app/issues/5358 // https://github.com/facebook/create-react-app/issues/5358
isEnvProduction && isEnvProduction &&
shouldInlineRuntimeChunk && shouldInlineRuntimeChunk &&
new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]), new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
// Makes some environment variables available in index.html. // Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.: // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="icon" href="%PUBLIC_URL%/favicon.ico"> // <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
@ -645,18 +642,18 @@ module.exports = function(webpackEnv) {
// Experimental hot reloading for React . // Experimental hot reloading for React .
// https://github.com/facebook/react/tree/master/packages/react-refresh // https://github.com/facebook/react/tree/master/packages/react-refresh
isEnvDevelopment && isEnvDevelopment &&
shouldUseReactRefresh && shouldUseReactRefresh &&
new ReactRefreshWebpackPlugin({ new ReactRefreshWebpackPlugin({
overlay: { overlay: {
entry: webpackDevClientEntry, entry: webpackDevClientEntry,
// The expected exports are slightly different from what the overlay exports, // The expected exports are slightly different from what the overlay exports,
// so an interop is included here to enable feedback on module-level errors. // so an interop is included here to enable feedback on module-level errors.
module: reactRefreshOverlayEntry, module: reactRefreshOverlayEntry,
// Since we ship a custom dev client and overlay integration, // Since we ship a custom dev client and overlay integration,
// the bundled socket handling logic can be eliminated. // the bundled socket handling logic can be eliminated.
sockIntegration: false, sockIntegration: false,
}, },
}), }),
// Watcher doesn't work well if you mistype casing in a path so we use // Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this. // a plugin that prints an error when you attempt to do this.
// See https://github.com/facebook/create-react-app/issues/240 // See https://github.com/facebook/create-react-app/issues/240
@ -666,14 +663,14 @@ module.exports = function(webpackEnv) {
// makes the discovery automatic so you don't have to restart. // makes the discovery automatic so you don't have to restart.
// See https://github.com/facebook/create-react-app/issues/186 // See https://github.com/facebook/create-react-app/issues/186
isEnvDevelopment && isEnvDevelopment &&
new WatchMissingNodeModulesPlugin(paths.appNodeModules), new WatchMissingNodeModulesPlugin(paths.appNodeModules),
isEnvProduction && isEnvProduction &&
new MiniCssExtractPlugin({ new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output // Options similar to the same options in webpackOptions.output
// both options are optional // both options are optional
filename: "static/css/[name].[contenthash:8].css", filename: "static/css/[name].[contenthash:8].css",
chunkFilename: "static/css/[name].[contenthash:8].chunk.css", chunkFilename: "static/css/[name].[contenthash:8].chunk.css",
}), }),
// Generate an asset manifest file with the following content: // Generate an asset manifest file with the following content:
// - "files" key: Mapping of all asset filenames to their corresponding // - "files" key: Mapping of all asset filenames to their corresponding
// output file so that tools can pick it up without having to parse // output file so that tools can pick it up without having to parse
@ -707,72 +704,72 @@ module.exports = function(webpackEnv) {
// Generate a service worker script that will precache, and keep up to date, // Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the webpack build. // the HTML & assets that are part of the webpack build.
isEnvProduction && isEnvProduction &&
fs.existsSync(swSrc) && fs.existsSync(swSrc) &&
new WorkboxWebpackPlugin.InjectManifest({ new WorkboxWebpackPlugin.InjectManifest({
swSrc, swSrc,
dontCacheBustURLsMatching: /\.[0-9a-f]{8}\./, dontCacheBustURLsMatching: /\.[0-9a-f]{8}\./,
exclude: [/\.map$/, /asset-manifest\.json$/, /LICENSE/], exclude: [/\.map$/, /asset-manifest\.json$/, /LICENSE/],
// Bump up the default maximum size (2mb) that's precached, // Bump up the default maximum size (2mb) that's precached,
// to make lazy-loading failure scenarios less likely. // to make lazy-loading failure scenarios less likely.
// See https://github.com/cra-template/pwa/issues/13#issuecomment-722667270 // See https://github.com/cra-template/pwa/issues/13#issuecomment-722667270
maximumFileSizeToCacheInBytes: 5 * 1024 * 1024, maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
}), }),
// TypeScript type checking // TypeScript type checking
useTypeScript && useTypeScript &&
new ForkTsCheckerWebpackPlugin({ new ForkTsCheckerWebpackPlugin({
typescript: resolve.sync("typescript", { typescript: resolve.sync("typescript", {
basedir: paths.appNodeModules, basedir: paths.appNodeModules,
}),
async: isEnvDevelopment,
checkSyntacticErrors: true,
resolveModuleNameModule: process.versions.pnp
? `${__dirname}/pnpTs.js`
: undefined,
resolveTypeReferenceDirectiveModule: process.versions.pnp
? `${__dirname}/pnpTs.js`
: undefined,
tsconfig: paths.appTsConfig,
reportFiles: [
// This one is specifically to match during CI tests,
// as micromatch doesn't match
// '../cra-template-typescript/template/src/App.tsx'
// otherwise.
"../**/src/**/*.{ts,tsx}",
"**/src/**/*.{ts,tsx}",
"!**/src/**/__tests__/**",
"!**/src/**/?(*.)(spec|test).*",
"!**/src/setupProxy.*",
"!**/src/setupTests.*",
],
silent: true,
// The formatter is invoked directly in WebpackDevServerUtils during development
formatter: isEnvProduction ? typescriptFormatter : undefined,
}), }),
async: isEnvDevelopment,
checkSyntacticErrors: true,
resolveModuleNameModule: process.versions.pnp ?
`${__dirname}/pnpTs.js` :
undefined,
resolveTypeReferenceDirectiveModule: process.versions.pnp ?
`${__dirname}/pnpTs.js` :
undefined,
tsconfig: paths.appTsConfig,
reportFiles: [
// This one is specifically to match during CI tests,
// as micromatch doesn't match
// '../cra-template-typescript/template/src/App.tsx'
// otherwise.
"../**/src/**/*.{ts,tsx}",
"**/src/**/*.{ts,tsx}",
"!**/src/**/__tests__/**",
"!**/src/**/?(*.)(spec|test).*",
"!**/src/setupProxy.*",
"!**/src/setupTests.*",
],
silent: true,
// The formatter is invoked directly in WebpackDevServerUtils during development
formatter: isEnvProduction ? typescriptFormatter : undefined,
}),
!disableESLintPlugin && !disableESLintPlugin &&
new ESLintPlugin({ new ESLintPlugin({
// Plugin options // Plugin options
extensions: ["js", "mjs", "jsx", "ts", "tsx"], extensions: ["js", "mjs", "jsx", "ts", "tsx"],
formatter: require.resolve("react-dev-utils/eslintFormatter"), formatter: require.resolve("react-dev-utils/eslintFormatter"),
eslintPath: require.resolve("eslint"), eslintPath: require.resolve("eslint"),
failOnError: !(isEnvDevelopment && emitErrorsAsWarnings), failOnError: !(isEnvDevelopment && emitErrorsAsWarnings),
context: paths.appSrc, context: paths.appSrc,
cache: true, cache: true,
cacheLocation: path.resolve( cacheLocation: path.resolve(
paths.appNodeModules, paths.appNodeModules,
".cache/.eslintcache" ".cache/.eslintcache"
), ),
// ESLint class options // ESLint class options
cwd: paths.appPath, cwd: paths.appPath,
resolvePluginsRelativeTo: __dirname, resolvePluginsRelativeTo: __dirname,
baseConfig: { baseConfig: {
extends: [require.resolve("eslint-config-react-app/base")], extends: [require.resolve("eslint-config-react-app/base")],
rules: { rules: {
...(!hasJsxRuntime && { ...(!hasJsxRuntime && {
"react/react-in-jsx-scope": "error", "react/react-in-jsx-scope": "error",
}), }),
},
}, },
}), },
}),
].filter(Boolean), ].filter(Boolean),
// Some libraries import Node modules but don't use them in the browser. // Some libraries import Node modules but don't use them in the browser.
// Tell webpack to provide empty mocks for them so importing them works. // Tell webpack to provide empty mocks for them so importing them works.
@ -790,4 +787,4 @@ module.exports = function(webpackEnv) {
// our own hints via the FileSizeReporter // our own hints via the FileSizeReporter
performance: false, performance: false,
}; };
}; };
Loading…
Cancel
Save