Browse Source

FIX | Change webpack config to prevent fail on build

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

401
config/webpack.config.js

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

Loading…
Cancel
Save