Implementation of webpack4 Component Library Building from 0
- 2021-09-24 21:30:32
- OfStack
Code separation
There are three methods of code separation:
Entry starting point: Use entry configuration to manually separate code. Prevent duplication: Use SplitChunksPlugin to remove duplication and separate chunk. Dynamic import: Separate code through inline function calls in modules.Dynamic Import (dynamic imports)
import() require.ensure
Prefetch/Preload Module (prefetch/preload module)
webpack v 4.6. 0 + adds support for prefetching and preloading.
When declaring import, you can have webpack output "resource hint (resource hint)" to inform the browser using these built-in directives:
prefetch (Prefetch): Resources that may be needed under some navigation in the future preload (preload): Resources may be required under current navigation
Detailed Explanation of Key Configuration Items
(1) mode: "pruduction"
Enable minification (code compression) and tree shaking (usedExports: true)
Automatically assign DefinePlugin: process. env. NODE_ENV = = = 'production'
(2) devtool
Introduction to source map
Production environment: source-map
Development environment: inline-source-map
(3) optimization
splitChunks
splitChunks: {
chunks: 'all', // Extract common modules loadash
// Will be 3 Square library (library) (For example lodash Or react ) to a separate vendor chunk In the document, it is a recommended practice
// Utilization client Long-term caching mechanism, hit cache to eliminate requests and reduce the number of requests to server Access to resources, while also ensuring that client Code and server Code version 1 To.
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
},
runtimeChunk
runtimeChunk: 'single' // Extract boot template Will runtime Code splitting 1 A single chunk
(5) output
// filename: '[name].[contenthash].js', // content hash Content changes will change
filename: 'webpack-numbers.js',
path: path.resolve(__dirname, 'dist'),
// Exposure library This is the name of the library import from 'webpackNumbers'
library: 'webpackNumbers',
libraryTarget: 'umd'
(6) plugins
HashedModuleIdsPlugin
const { HashedModuleIdsPlugin } = require('webpack');
plugins: [
// The module content will not change due to the increase and decrease of modules, and the long cache hit mechanism will be added
new HashedModuleIdsPlugin()
],
BundleAnalyzerPlugin
Analyze packaging code
const {BundleAnalyzerPlugin} = require('webpack-bundle-analyzer');
plugins: [
new BundleAnalyzerPlugin()
]