Comparison of three default configurations of webpack5 modes

The sound of clouds 2021-05-03 18:20:27
comparison default configurations webpack5 webpack


although webpack Documents The configuration of default configuration items for three modes has been given in , But I'm still curious, except for these listed configurations , Is there any difference between other configurations ?

Export configuration objects of three modes

webpack The version is V5.36.1, The source code path to get the default configuration is webpack/lib/WebpackOptionsDefaulter.js , The source code of the file is as follows :

const { applyWebpackOptionsDefaults } = require("./config/defaults");
const { getNormalizedWebpackOptions } = require("./config/normalization");
class WebpackOptionsDefaulter {
process(options) {
options = getNormalizedWebpackOptions(options);
applyWebpackOptionsDefaults(options);
return options;
}
}
module.exports = WebpackOptionsDefaulter;
 Copy code 

Our goal is to capture the options, So we don't need to worry about the specific code of the two modules introduced here , From this code, we know that , Just go through WebpackOptionsDefaulter Instance method of process, You can get the specific configuration of each mode , Get the default configuration code as follows :

// getWebpackConfig.js
const fs = require('fs');
const {stringify} = require('javascript-stringify');
const WebpackDefaulterClass = require('webpack/lib/WebpackOptionsDefaulter');
const webpackDefaulter = new WebpackDefaulterClass();
['none','development','production'].forEach(mode => generateOptions(mode));
function generateOptions(mode) {
const options = webpackDefaulter.process({mode});
fs.writeFileSync(`./webpack.${mode}.config.js`, 'module.exports = ' + stringify(options));
}
 Copy code 

Execute on the command line node getWebpackConfig after , Output the corresponding configuration to the corresponding file , Then format the file , Just get ready .

The configuration differences of the three modes

1、cache

  • production The model is false

  • development The model is

    {
    cache: {
    type: 'memory',
    maxGenerations: Infinity
    }
    }
     Copy code 
  • none The model is false

cache The function of configuration is to replace the one that has been processed module and chunk, To speed up the build .production Patterns are generally packaged as new builds , So the default is no cache , But in the development process , Construction speed directly affects development efficiency , therefore development In mode ,webpack Will use cache .

type Support configuration is filesystem and memory, File system and memory cache , The pursuit of fast development mode , So the configuration is memory.

maxGenerations yes 5.30.0+ Version only configuration , This configuration sets the lifetime of the memory cache that is not used , The configuration value type is number, Set to Infinity It means to keep it all the time .

2、devtool

  • production The model is false

  • none The model is false

  • development The configuration in is :

    {
    devtool: 'eval'
    }
     Copy code 

This configuration specifies source map The format of ,false Then it does not generate source map,development The default mode is eval Format ,eval The format features each module uses eval() perform , And both have //@ sourceURL. This option builds very quickly . The main disadvantages are , Because it maps to the converted code , Instead of mapping to the original code ( Not from loader In order to get source map), So it can't display the number of lines correctly .

If the construction speed is not so high , have access to eval-cheap-module-source-map replace eval,eval-cheap-module-source-map At the expense of building speed , However, you can provide a mapping of the number of lines of original code .

3、module.unsafeCache

  • production The model is false

  • none The model is false

  • development The configuration is :

    // const NODE_MODULES_REGEXP = /[\\/]node_modules[\\/]/i;
    {
    unsafeCache: module => {
    const name = module.nameForCondition();
    return name && NODE_MODULES_REGEXP.test(name);
    },
    }
     Copy code 

This configuration indicates whether to cache the resolution of module requests ,development Of unsafeCache Configuration representation , If through the module nameForCondition The module path obtained by method exists , And is node_modules Module in , Cache .

4、optimization.splitChunks.hidePathInfo

This configuration indicates that due to optimization.splitChunks.maxSize The extracted file name created by configuration hides the path information , Whether the derived name is a module name or a hash value .

  • production The model is true
  • development The model is false
  • none The model is false

When chunk When there is already a name , Each part gets a new name derived from that name . according to optimization.splitChunks.hidePathInfo Value , It will add a key derived from the first module name or its hash value .

5、optimization.splitChunks.minRemainingSize

  • production The model is undefined( I'm going to use theta splitChunks.minSize Value )
  • development The model is 0
  • none The model is undefined( I'm going to use theta splitChunks.minSize Value )

webpack 5 Introduced in splitChunks.minRemainingSize Options , Avoid zero size modules by ensuring that the size of the smallest remaining blocks after splitting is greater than the limit . In development mode, the default is 0. In other cases ,splitChunks.minRemainingSize The default value is splitChunks.minSize Value , So, with the exception of a few cases that require excessive intervention , No need to specify it manually .

6、optimization.splitChunks.enforceSizeThreshold

  • production The model is 5000
  • development The model is 3000
  • none The model is 3000

7、optimization.emitOnErrors

  • prodution The model is false
  • development The model is true
  • none The model is true

This configuration indicates that when an error is encountered during compilation , Whether resources are still generated , So when there is an error in the production build process, the compilation will be terminated , And development doesn't stop , But an error will be reported when the code is running .

8、optimization.flagIncludedChunks

  • prodution The model is true
  • development The model is false
  • none The model is false

Set to true when ,webpack Mark as other chunk Subset of chunk, In the already loaded large chunk You don't have to load subsets chunk.

9、optimization.moduleIds and optimization.chunkIds

The two configurations are modules id and chunk id Choose a name algorithm , All three modes of this configuration are different .

  • production In this mode, it is deterministic, Module names are hashed to smaller values .

  • development In this mode, it is named, The module name is readable , Convenient debugging .

  • none In this mode, it is natural, Module names are numbers in order of use ID.

10、optimization.sideEffects

  • production The model is true
  • development The model is flag
  • none The model is flag

inform webpack To identify package.json Medium side effect Mark or rule , To skip modules that do not contain side effects when the export is not used and marked .

11、optimization.usedExports

  • production The model is true
  • development The model is false
  • none The model is false

It tells Webpack To determine the export used by each module . With it ,Webpack We'll add extra things like /* unused harmony export */ Notes like that , In the following compression steps, we can use .

12、optimization.innerGraph

inform webpack Export unused content , Implement internal graphic analysis .

  • production The model is true
  • development The model is false
  • none The model is false

13、optimization.mangleExports

This configuration allows control of export processing .

  • production The model is true, Equivalent to deterministic, Abbreviation form - Usually two characters — Add or remove export It doesn't change . For long term caching .
  • development The model is false, Keep the original name , It's good for reading and debugging .
  • none The model is false, Keep the original name , It's good for reading and debugging .

14、optimization.concatenateModules

This configuration tells webpack Whether to safely combine modules into one module according to the module diagram .

  • production The model is true
  • development The model is false
  • none The model is false

15、optimization.realContentHash

Resources generate and generate the right resource content hash after , Add an extra hash.

  • production The model is true
  • development The model is false
  • none The model is false

16、optimization.minimize

tell webpack Use TerserPlugin Or in optimization.minimizer Option bundle.

  • production In the mode is true
  • development The model is false
  • none The model is false

Three modes of optimization.minimizer The configuration is the same :

minimizer: [{
apply: compiler => {
// Lazy load the Terser plugin
const TerserPlugin = require("terser-webpack-plugin");
new TerserPlugin({
terserOptions: {
compress: {
passes: 2
}
}
}).apply(compiler);
}
}],
 Copy code 

17、optimization.nodeEnv

The configuration assigns a value to process.env.NODE_ENV, If it is false, The value is not assigned .

  • production The model is production
  • development The model is development
  • none The model is false

18、performance

With this configuration, you can set how to prompt when the build resource exceeds the limit .

  • production The mode is configured to :

    performance: {
    maxAssetSize: 250000, // Maximum resource size 250KB
    maxEntrypointSize: 250000, // Maximum entry resource size 250KB
    hints: 'warning' // If the limit is exceeded, only a warning will be given 
    },
     Copy code 
  • development The model is false

  • none The model is false

Three model goals

From the differences of the above analysis, we can verify the differences of the goals of the three models again .

production The pattern is for the efficiency of resource access in the production environment .

development Pattern is for debugging efficiency of development environment .

none Patterns don't usually work , It's basically the same as development Same pattern , There are some deficiencies in caching and development debugging , So basically don't choose none Pattern .

Configuration objects of three modes

mode: 'none'

module.exports = {
amd: undefined,
bail: undefined,
cache: false,
context: '/Users/test',
dependencies: undefined,
devServer: undefined,
devtool: false,
entry: {
main: {
'import': ['./src']
}
},
experiments: {
topLevelAwait: false,
syncWebAssembly: false,
asyncWebAssembly: false,
outputModule: false
},
externals: undefined,
externalsPresets: {
web: true,
node: false,
nwjs: false,
electron: false,
electronMain: false,
electronPreload: false,
electronRenderer: false
},
externalsType: 'var',
ignoreWarnings: undefined,
infrastructureLogging: {},
loader: {
target: 'web'
},
mode: 'none',
module: {
noParse: undefined,
unsafeCache: false,
parser: {
javascript: {
unknownContextRequest: '.',
unknownContextRegExp: false,
unknownContextRecursive: true,
unknownContextCritical: true,
exprContextRequest: '.',
exprContextRegExp: false,
exprContextRecursive: true,
exprContextCritical: true,
wrappedContextRegExp: /.*/,
wrappedContextRecursive: true,
wrappedContextCritical: false,
strictExportPresence: false,
strictThisContextOnImports: false
},
asset: {
dataUrlCondition: {
maxSize: 8096
}
}
},
generator: {},
defaultRules: [{
mimetype: 'application/node',
type: 'javascript/auto'
}, {
test: /\.json$/i,
type: 'json'
}, {
mimetype: 'application/json',
type: 'json'
}, {
test: /\.mjs$/i,
type: 'javascript/esm',
resolve: {
byDependency: {
esm: {
fullySpecified: true
}
}
}
}, {
test: /\.js$/i,
descriptionData: {
type: 'module'
},
type: 'javascript/esm',
resolve: {
byDependency: {
esm: {
fullySpecified: true
}
}
}
}, {
test: /\.cjs$/i,
type: 'javascript/dynamic'
}, {
test: /\.js$/i,
descriptionData: {
type: 'commonjs'
},
type: 'javascript/dynamic'
}, {
mimetype: {
or: ['text/javascript', 'application/javascript']
},
type: 'javascript/esm',
resolve: {
byDependency: {
esm: {
fullySpecified: true
}
}
}
}, {
dependency: 'url',
type: 'asset/resource'
}],
rules: []
},
name: undefined,
node: {
global: true,
__filename: 'mock',
__dirname: 'mock'
},
optimization: {
runtimeChunk: false,
splitChunks: {
defaultSizeTypes: ['javascript', 'unknown'],
cacheGroups: {
'default': {
idHint: '',
reuseExistingChunk: true,
minChunks: 2,
priority: -20
},
defaultVendors: {
idHint: 'vendors',
reuseExistingChunk: true,
test: /[\\/]node_modules[\\/]/i,
priority: -10
}
},
hidePathInfo: false,
chunks: 'async',
usedExports: false,
minChunks: 1,
minSize: 10000,
minRemainingSize: undefined,
enforceSizeThreshold: 30000,
maxAsyncRequests: Infinity,
maxInitialRequests: Infinity,
automaticNameDelimiter: '-'
},
emitOnErrors: true,
removeAvailableModules: false,
removeEmptyChunks: true,
mergeDuplicateChunks: true,
flagIncludedChunks: false,
moduleIds: 'natural',
chunkIds: 'natural',
sideEffects: 'flag',
providedExports: true,
usedExports: false,
innerGraph: false,
mangleExports: false,
concatenateModules: false,
checkWasmTypes: false,
mangleWasmImports: false,
portableRecords: false,
realContentHash: false,
minimize: false,
minimizer: [{
apply: compiler => {
// Lazy load the Terser plugin
const TerserPlugin = require("terser-webpack-plugin");
new TerserPlugin({
terserOptions: {
compress: {
passes: 2
}
}
}).apply(compiler);
}
}],
nodeEnv: false
},
output: {
assetModuleFilename: '[hash][ext][query]',
charset: true,
chunkFilename: '[name].js',
chunkFormat: 'array-push',
chunkLoading: 'jsonp',
chunkLoadingGlobal: 'webpackChunktest_npm',
chunkLoadTimeout: 120000,
clean: undefined,
compareBeforeEmit: true,
crossOriginLoading: false,
devtoolFallbackModuleFilenameTemplate: undefined,
devtoolModuleFilenameTemplate: undefined,
devtoolNamespace: 'test-npm',
environment: {
arrowFunction: true,
'const': true,
destructuring: true,
forOf: true,
bigIntLiteral: undefined,
dynamicImport: undefined,
module: undefined
},
enabledChunkLoadingTypes: ['jsonp', 'import-scripts'],
enabledLibraryTypes: [],
enabledWasmLoadingTypes: ['fetch'],
filename: '[name].js',
globalObject: 'self',
hashDigest: 'hex',
hashDigestLength: 20,
hashFunction: 'md4',
hashSalt: undefined,
hotUpdateChunkFilename: '[id].[fullhash].hot-update.js',
hotUpdateGlobal: 'webpackHotUpdatetest_npm',
hotUpdateMainFilename: '[runtime].[fullhash].hot-update.json',
iife: true,
importFunctionName: 'import',
importMetaName: 'import.meta',
scriptType: false,
library: undefined,
module: false,
path: '/Users/test/dist',
pathinfo: false,
publicPath: 'auto',
sourceMapFilename: '[file].map[query]',
sourcePrefix: undefined,
strictModuleExceptionHandling: false,
uniqueName: 'test-npm',
wasmLoading: 'fetch',
webassemblyModuleFilename: '[hash].module.wasm',
workerChunkLoading: 'import-scripts',
workerWasmLoading: 'fetch'
},
parallelism: 100,
performance: false,
plugins: [],
profile: false,
recordsInputPath: false,
recordsOutputPath: false,
resolve: {
byDependency: {
wasm: {
conditionNames: ['import', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
esm: {
conditionNames: ['import', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
loaderImport: {
conditionNames: ['import', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
worker: {
conditionNames: ['import', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...'],
preferRelative: true
},
commonjs: {
conditionNames: ['require', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
amd: {
conditionNames: ['require', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
loader: {
conditionNames: ['require', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
unknown: {
conditionNames: ['require', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
undefined: {
conditionNames: ['require', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
url: {
preferRelative: true
}
},
cache: false,
modules: ['node_modules'],
conditionNames: ['webpack', 'production', 'browser'],
mainFiles: ['index'],
extensions: [],
aliasFields: [],
exportsFields: ['exports'],
roots: ['/Users/test'],
mainFields: ['main']
},
resolveLoader: {
cache: false,
conditionNames: ['loader', 'require', 'node'],
exportsFields: ['exports'],
mainFields: ['loader', 'main'],
extensions: ['.js'],
mainFiles: ['index']
},
snapshot: {
resolveBuildDependencies: {
timestamp: true,
hash: true
},
buildDependencies: {
timestamp: true,
hash: true
},
resolve: {
timestamp: true
},
module: {
timestamp: true
},
immutablePaths: [],
managedPaths: ['/Users/test/node_modules']
},
stats: {},
target: 'web',
watch: false,
watchOptions: {}
}
 Copy code 

mode: 'development'

module.exports = {
amd: undefined,
bail: undefined,
cache: {
type: 'memory',
maxGenerations: Infinity
},
context: '/Users/test',
dependencies: undefined,
devServer: undefined,
devtool: 'eval',
entry: {
main: {
'import': ['./src']
}
},
experiments: {
topLevelAwait: false,
syncWebAssembly: false,
asyncWebAssembly: false,
outputModule: false
},
externals: undefined,
externalsPresets: {
web: true,
node: false,
nwjs: false,
electron: false,
electronMain: false,
electronPreload: false,
electronRenderer: false
},
externalsType: 'var',
ignoreWarnings: undefined,
infrastructureLogging: {},
loader: {
target: 'web'
},
mode: 'development',
module: {
noParse: undefined,
unsafeCache: module => {
const name = module.nameForCondition();
return name && NODE_MODULES_REGEXP.test(name);
},
parser: {
javascript: {
unknownContextRequest: '.',
unknownContextRegExp: false,
unknownContextRecursive: true,
unknownContextCritical: true,
exprContextRequest: '.',
exprContextRegExp: false,
exprContextRecursive: true,
exprContextCritical: true,
wrappedContextRegExp: /.*/,
wrappedContextRecursive: true,
wrappedContextCritical: false,
strictExportPresence: false,
strictThisContextOnImports: false
},
asset: {
dataUrlCondition: {
maxSize: 8096
}
}
},
generator: {},
defaultRules: [{
mimetype: 'application/node',
type: 'javascript/auto'
}, {
test: /\.json$/i,
type: 'json'
}, {
mimetype: 'application/json',
type: 'json'
}, {
test: /\.mjs$/i,
type: 'javascript/esm',
resolve: {
byDependency: {
esm: {
fullySpecified: true
}
}
}
}, {
test: /\.js$/i,
descriptionData: {
type: 'module'
},
type: 'javascript/esm',
resolve: {
byDependency: {
esm: {
fullySpecified: true
}
}
}
}, {
test: /\.cjs$/i,
type: 'javascript/dynamic'
}, {
test: /\.js$/i,
descriptionData: {
type: 'commonjs'
},
type: 'javascript/dynamic'
}, {
mimetype: {
or: ['text/javascript', 'application/javascript']
},
type: 'javascript/esm',
resolve: {
byDependency: {
esm: {
fullySpecified: true
}
}
}
}, {
dependency: 'url',
type: 'asset/resource'
}],
rules: []
},
name: undefined,
node: {
global: true,
__filename: 'mock',
__dirname: 'mock'
},
optimization: {
runtimeChunk: false,
splitChunks: {
defaultSizeTypes: ['javascript', 'unknown'],
cacheGroups: {
'default': {
idHint: '',
reuseExistingChunk: true,
minChunks: 2,
priority: -20
},
defaultVendors: {
idHint: 'vendors',
reuseExistingChunk: true,
test: /[\\/]node_modules[\\/]/i,
priority: -10
}
},
hidePathInfo: false,
chunks: 'async',
usedExports: false,
minChunks: 1,
minSize: 10000,
minRemainingSize: 0,
enforceSizeThreshold: 30000,
maxAsyncRequests: Infinity,
maxInitialRequests: Infinity,
automaticNameDelimiter: '-'
},
emitOnErrors: true,
removeAvailableModules: false,
removeEmptyChunks: true,
mergeDuplicateChunks: true,
flagIncludedChunks: false,
moduleIds: 'named',
chunkIds: 'named',
sideEffects: 'flag',
providedExports: true,
usedExports: false,
innerGraph: false,
mangleExports: false,
concatenateModules: false,
checkWasmTypes: false,
mangleWasmImports: false,
portableRecords: false,
realContentHash: false,
minimize: false,
minimizer: [{
apply: compiler => {
// Lazy load the Terser plugin
const TerserPlugin = require("terser-webpack-plugin");
new TerserPlugin({
terserOptions: {
compress: {
passes: 2
}
}
}).apply(compiler);
}
}],
nodeEnv: 'development'
},
output: {
assetModuleFilename: '[hash][ext][query]',
charset: true,
chunkFilename: '[name].js',
chunkFormat: 'array-push',
chunkLoading: 'jsonp',
chunkLoadingGlobal: 'webpackChunktest_npm',
chunkLoadTimeout: 120000,
clean: undefined,
compareBeforeEmit: true,
crossOriginLoading: false,
devtoolFallbackModuleFilenameTemplate: undefined,
devtoolModuleFilenameTemplate: undefined,
devtoolNamespace: 'test-npm',
environment: {
arrowFunction: true,
'const': true,
destructuring: true,
forOf: true,
bigIntLiteral: undefined,
dynamicImport: undefined,
module: undefined
},
enabledChunkLoadingTypes: ['jsonp', 'import-scripts'],
enabledLibraryTypes: [],
enabledWasmLoadingTypes: ['fetch'],
filename: '[name].js',
globalObject: 'self',
hashDigest: 'hex',
hashDigestLength: 20,
hashFunction: 'md4',
hashSalt: undefined,
hotUpdateChunkFilename: '[id].[fullhash].hot-update.js',
hotUpdateGlobal: 'webpackHotUpdatetest_npm',
hotUpdateMainFilename: '[runtime].[fullhash].hot-update.json',
iife: true,
importFunctionName: 'import',
importMetaName: 'import.meta',
scriptType: false,
library: undefined,
module: false,
path: '/Users/test/dist',
pathinfo: true,
publicPath: 'auto',
sourceMapFilename: '[file].map[query]',
sourcePrefix: undefined,
strictModuleExceptionHandling: false,
uniqueName: 'test-npm',
wasmLoading: 'fetch',
webassemblyModuleFilename: '[hash].module.wasm',
workerChunkLoading: 'import-scripts',
workerWasmLoading: 'fetch'
},
parallelism: 100,
performance: false,
plugins: [],
profile: false,
recordsInputPath: false,
recordsOutputPath: false,
resolve: {
byDependency: {
wasm: {
conditionNames: ['import', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
esm: {
conditionNames: ['import', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
loaderImport: {
conditionNames: ['import', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
worker: {
conditionNames: ['import', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...'],
preferRelative: true
},
commonjs: {
conditionNames: ['require', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
amd: {
conditionNames: ['require', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
loader: {
conditionNames: ['require', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
unknown: {
conditionNames: ['require', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
undefined: {
conditionNames: ['require', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
url: {
preferRelative: true
}
},
cache: true,
modules: ['node_modules'],
conditionNames: ['webpack', 'development', 'browser'],
mainFiles: ['index'],
extensions: [],
aliasFields: [],
exportsFields: ['exports'],
roots: ['/Users/test'],
mainFields: ['main']
},
resolveLoader: {
cache: true,
conditionNames: ['loader', 'require', 'node'],
exportsFields: ['exports'],
mainFields: ['loader', 'main'],
extensions: ['.js'],
mainFiles: ['index']
},
snapshot: {
resolveBuildDependencies: {
timestamp: true,
hash: true
},
buildDependencies: {
timestamp: true,
hash: true
},
resolve: {
timestamp: true
},
module: {
timestamp: true
},
immutablePaths: [],
managedPaths: ['/Users/test/node_modules']
},
stats: {},
target: 'web',
watch: false,
watchOptions: {}
}
 Copy code 

mode: 'production'

module.exports = {
amd: undefined,
bail: undefined,
cache: false,
context: '/Users/test',
dependencies: undefined,
devServer: undefined,
devtool: false,
entry: {
main: {
'import': ['./src']
}
},
experiments: {
topLevelAwait: false,
syncWebAssembly: false,
asyncWebAssembly: false,
outputModule: false
},
externals: undefined,
externalsPresets: {
web: true,
node: false,
nwjs: false,
electron: false,
electronMain: false,
electronPreload: false,
electronRenderer: false
},
externalsType: 'var',
ignoreWarnings: undefined,
infrastructureLogging: {},
loader: {
target: 'web'
},
mode: 'production',
module: {
noParse: undefined,
unsafeCache: false,
parser: {
javascript: {
unknownContextRequest: '.',
unknownContextRegExp: false,
unknownContextRecursive: true,
unknownContextCritical: true,
exprContextRequest: '.',
exprContextRegExp: false,
exprContextRecursive: true,
exprContextCritical: true,
wrappedContextRegExp: /.*/,
wrappedContextRecursive: true,
wrappedContextCritical: false,
strictExportPresence: false,
strictThisContextOnImports: false
},
asset: {
dataUrlCondition: {
maxSize: 8096
}
}
},
generator: {},
defaultRules: [{
mimetype: 'application/node',
type: 'javascript/auto'
}, {
test: /\.json$/i,
type: 'json'
}, {
mimetype: 'application/json',
type: 'json'
}, {
test: /\.mjs$/i,
type: 'javascript/esm',
resolve: {
byDependency: {
esm: {
fullySpecified: true
}
}
}
}, {
test: /\.js$/i,
descriptionData: {
type: 'module'
},
type: 'javascript/esm',
resolve: {
byDependency: {
esm: {
fullySpecified: true
}
}
}
}, {
test: /\.cjs$/i,
type: 'javascript/dynamic'
}, {
test: /\.js$/i,
descriptionData: {
type: 'commonjs'
},
type: 'javascript/dynamic'
}, {
mimetype: {
or: ['text/javascript', 'application/javascript']
},
type: 'javascript/esm',
resolve: {
byDependency: {
esm: {
fullySpecified: true
}
}
}
}, {
dependency: 'url',
type: 'asset/resource'
}],
rules: []
},
name: undefined,
node: {
global: true,
__filename: 'mock',
__dirname: 'mock'
},
optimization: {
runtimeChunk: false,
splitChunks: {
defaultSizeTypes: ['javascript', 'unknown'],
cacheGroups: {
'default': {
idHint: '',
reuseExistingChunk: true,
minChunks: 2,
priority: -20
},
defaultVendors: {
idHint: 'vendors',
reuseExistingChunk: true,
test: /[\\/]node_modules[\\/]/i,
priority: -10
}
},
hidePathInfo: true,
chunks: 'async',
usedExports: true,
minChunks: 1,
minSize: 20000,
minRemainingSize: undefined,
enforceSizeThreshold: 50000,
maxAsyncRequests: 30,
maxInitialRequests: 30,
automaticNameDelimiter: '-'
},
emitOnErrors: false,
removeAvailableModules: false,
removeEmptyChunks: true,
mergeDuplicateChunks: true,
flagIncludedChunks: true,
moduleIds: 'deterministic',
chunkIds: 'deterministic',
sideEffects: true,
providedExports: true,
usedExports: true,
innerGraph: true,
mangleExports: true,
concatenateModules: true,
checkWasmTypes: true,
mangleWasmImports: false,
portableRecords: false,
realContentHash: true,
minimize: true,
minimizer: [{
apply: compiler => {
// Lazy load the Terser plugin
const TerserPlugin = require("terser-webpack-plugin");
new TerserPlugin({
terserOptions: {
compress: {
passes: 2
}
}
}).apply(compiler);
}
}],
nodeEnv: 'production'
},
output: {
assetModuleFilename: '[hash][ext][query]',
charset: true,
chunkFilename: '[name].js',
chunkFormat: 'array-push',
chunkLoading: 'jsonp',
chunkLoadingGlobal: 'webpackChunktest_npm',
chunkLoadTimeout: 120000,
clean: undefined,
compareBeforeEmit: true,
crossOriginLoading: false,
devtoolFallbackModuleFilenameTemplate: undefined,
devtoolModuleFilenameTemplate: undefined,
devtoolNamespace: 'test-npm',
environment: {
arrowFunction: true,
'const': true,
destructuring: true,
forOf: true,
bigIntLiteral: undefined,
dynamicImport: undefined,
module: undefined
},
enabledChunkLoadingTypes: ['jsonp', 'import-scripts'],
enabledLibraryTypes: [],
enabledWasmLoadingTypes: ['fetch'],
filename: '[name].js',
globalObject: 'self',
hashDigest: 'hex',
hashDigestLength: 20,
hashFunction: 'md4',
hashSalt: undefined,
hotUpdateChunkFilename: '[id].[fullhash].hot-update.js',
hotUpdateGlobal: 'webpackHotUpdatetest_npm',
hotUpdateMainFilename: '[runtime].[fullhash].hot-update.json',
iife: true,
importFunctionName: 'import',
importMetaName: 'import.meta',
scriptType: false,
library: undefined,
module: false,
path: '/Users/test/dist',
pathinfo: false,
publicPath: 'auto',
sourceMapFilename: '[file].map[query]',
sourcePrefix: undefined,
strictModuleExceptionHandling: false,
uniqueName: 'test-npm',
wasmLoading: 'fetch',
webassemblyModuleFilename: '[hash].module.wasm',
workerChunkLoading: 'import-scripts',
workerWasmLoading: 'fetch'
},
parallelism: 100,
performance: {
maxAssetSize: 250000,
maxEntrypointSize: 250000,
hints: 'warning'
},
plugins: [],
profile: false,
recordsInputPath: false,
recordsOutputPath: false,
resolve: {
byDependency: {
wasm: {
conditionNames: ['import', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
esm: {
conditionNames: ['import', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
loaderImport: {
conditionNames: ['import', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
worker: {
conditionNames: ['import', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...'],
preferRelative: true
},
commonjs: {
conditionNames: ['require', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
amd: {
conditionNames: ['require', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
loader: {
conditionNames: ['require', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
unknown: {
conditionNames: ['require', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
undefined: {
conditionNames: ['require', 'module', '...'],
extensions: ['.js', '.json', '.wasm'],
aliasFields: ['browser'],
mainFields: ['browser', 'module', '...']
},
url: {
preferRelative: true
}
},
cache: false,
modules: ['node_modules'],
conditionNames: ['webpack', 'production', 'browser'],
mainFiles: ['index'],
extensions: [],
aliasFields: [],
exportsFields: ['exports'],
roots: ['/Users/test'],
mainFields: ['main']
},
resolveLoader: {
cache: false,
conditionNames: ['loader', 'require', 'node'],
exportsFields: ['exports'],
mainFields: ['loader', 'main'],
extensions: ['.js'],
mainFiles: ['index']
},
snapshot: {
resolveBuildDependencies: {
timestamp: true,
hash: true
},
buildDependencies: {
timestamp: true,
hash: true
},
resolve: {
timestamp: true,
hash: true
},
module: {
timestamp: true,
hash: true
},
immutablePaths: [],
managedPaths: ['/Users/test/node_modules']
},
stats: {},
target: 'web',
watch: false,
watchOptions: {}
}
 Copy code 

A little thought

webpack The configuration of is very complicated , The details involved in the construction process are configurable , The feeling is that it increases the cost of learning , The context of many configurations , Reading the document may not be able to understand the role , Too much effort will be put into studying the source code , Often the input-output ratio is very low .

In general development scenarios , We don't need to be so careful about webpack Configuration for learning ,webpack Best practice configuration has been provided through patterns , And what we have to do , It's just a designation mode, Then configure as appropriate entry、output、loader、plugin nothing more . Only when the default configuration cannot meet the actual situation , We need to understand it better , It's a rare case , We should focus on more meaningful business value .

版权声明
本文为[The sound of clouds]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210503181828124Q.html

  1. 浅谈 React 中的 XSS 攻击
  2. XSS attack in react
  3. 自学前端教程整理,附不容错过的前端100篇文章合集
  4. Self taught front-end tutorial collation, with a collection of 100 front-end articles that can not be missed
  5. 使用OpenTracing跟踪Go中的HTTP请求延迟
  6. Using opentracing to track HTTP request latency in go
  7. Encapsulating databinding allows you to write less than 10000 lines of code
  8. 03-HTML5标签-HTML5极速入门
  9. 03-html5 tag-html5 quick start
  10. LayUI - 极易上手拿来即用的前端 UI 框架
  11. Layui - easy to use front end UI framework
  12. Interpretation of lodash source code (1)
  13. Why is the first parameter of node family callback error?
  14. 报告:JavaScript 开发者达1380 万,C#超越 PHP,Rust 增长最快
  15. Report: Javascript developers reach 13.8 million, C surpasses PHP, and rust grows fastest
  16. 小白前端入门笔记(10),怎么设置网站内部的超链接?
  17. How to set up hyperlinks inside the website?
  18. Using node and socket to realize online chat room
  19. The core competitiveness of Vue: data bidirectional binding
  20. React configuration agent
  21. CSS layout
  22. Application scenario explanation of Vue dynamic component
  23. Redux learning notes 04 -- using multiple reducers to manage data
  24. After three months of typescript writing, what have I learned?
  25. Node family - what is a callback?
  26. React -- a simple implementation of render & create element
  27. JS learning simple usage of jquery
  28. Seamless love
  29. 小白前端入门笔记(12),设置哑链接
  30. Small white front-end entry notes (12), set dumb links
  31. Vue2. X opens composition API and TSX
  32. Interview record and thinking of social recruitment for one and a half years (Alibaba, Tencent, baidu offer)
  33. Flex learning notes
  34. The most essential closure article in the eastern hemisphere
  35. 2021-05-03 hot news
  36. Sword finger offer -- reverse order pair in array (JS Implementation)
  37. Working process of scaffold
  38. Use decorator mode to strengthen your fetch
  39. [JS] scope (Introduction)
  40. Employment information statistics network (interface document)
  41. Analysis of MVC
  42. [middle stage] please stay and join me in the backstage
  43. Understanding front end garbage collection
  44. [continuous update] front end special style implementation
  45. Flutter product analysis and package reduction scheme
  46. XPath positioning
  47. 前端开发css中的flex布局的使用
  48. The use of flex layout in front end development CSS
  49. JQuery核心函数和静态方法
  50. JQuery core functions and static methods
  51. Node family - understanding of blocking and non blocking
  52. 热点微前端Microfrontend的讨论:谷歌AdWords是真实的微前端
  53. Vue source code analysis (2) initproxy initialization proxy
  54. What's TM called react diff
  55. Summary of common front end data structure
  56. Useeffect in hooks
  57. [encapsulation 02 design pattern] Command pattern, share meta pattern, combination pattern, proxy pattern, strategy pattern
  58. Front end notes: virtual Dom and diff of vue2. X
  59. The best code scanning plug-in of flutter
  60. The simplest plug-in for rights management of flutter