preface
Webpack5.0 project configuration is as follows, direct CV can run use! An occasional tidying up can give development a little 🤏 help! Gitee address: gitee.com/licong777/w…
Here is my package.json file to configure the dependencies needed for the project. For reference:
{" name ":" webpack5 ", "version" : "1.0.0", "description" : ""," main ":" index. Js ", "scripts" : {" test ", "echo \" Error: no test specified\" && exit 1", "serve": "cross-env NODE_ENV=development webpack serve --config build/webpack.dev.config.js", "build": "cross-env NODE_ENV=production webpack --config build/webpack.prod.config.js" }, "keywords": [], "author": < span style = "box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 14px! Important; word-break: inherit! Important;" "^ 7.14.5 @", "Babel/plugin - proposal - optional - chaining" : "^ 7.14.5", "@ Babel/plugin - transform - runtime" : "^ 7.14.5 @", "Babel/polyfill" : "^ 7.12.1", "@ Babel/preset - env" : "^ 7.14.8", "@ Babel/runtime - corejs2" : "^ 7.14.8 autoprefixer", ""," ^ 10.3.1 ", "Babel - loader" : "^ 8.2.2", "compression will - webpack - plugin" : "^ 8.0.1 copy - webpack -", "plugins" : "^ 9.0.1", "cross - env" : "^ 7.0.3", "CSS - loader" : "^3.0.2", "html-minimizer-webpack-plugin": "^3.1.1", "html-webpack-plugin": "^ 5.3.2" and "less", "^ 4.4.1", "less - loader" : "^ 10.0.1", "mini - CSS - extract - the plugin" : "^ 2.1.0", "path - browserify" : "^" 1.0.1, "postcss - loader" : "^ 6.1.1", "sass - resources - loader" : "^ 2.2.3", "style - loader" : "^ 3.2.1 terser - webpack -", "plugins" : "^ 5.1.4 ensuring", "vue - loader" : "^ 15.9.6", "vue - the template - the compiler" : "^ 2.6.14", "webpack" : "^ 5.46.0 webpack -", "cli" : "^ 4.7.2", "webpack - dev - server" : "^ 3.11.2", "webpack - merge" : "^ 5.8.0"}}Copy the code
Begin to build
The lowest version of Node.js running WebPack 5 is 10.13.0 (LTS). Installation depend on the way to use taobao mirror can not perform the installation of service: NPM CNPM I – g – registry=http://registry.npm.taobao.org
First run CNPM init-y to generate package.json to initialize the project configuration file and install webPack-related dependency packages
cnpm i webpack webpack-dev-server webpack-merge -D
Webpack can be thought of as a module packer. Webpack – A simple CLI client used to connect services using the WebPack protocol. Webpack-dev-server is a small express server officially provided by WebPack. It provides Web services for resource files generated by WebPack. Webpack-merge is used to merge files used in different environments.
Core Attribute Configuration
- entry
One or more starting points for the application packaging process. If an array is passed in, all entries are processed. This is where the @babel/ Polyfill plug-in can be introduced to transform the new API and resolve syntactic compatibility issues
entry: [
'@babel/polyfill',
resolve('../src/main.js')
]
Copy the code
- output
To indicate how webpack should package the output, you can configure the attribute here. ChunkFilename is used in conjunction with the webpackChunkName lazily loaded by the VUE route to generate the output filename. The clean property was added in v5 to clean up the package directory.
output: { path: resolve('.. /dist'), filename: 'js/[name].js', chunkFilename: 'js/[name].js', clean: true },Copy the code
- module
Configure properties to handle different types of modules in the project. Loader for file conversion is configured in module.rules.
Working with JS files
@babel/core is the interpreter itself, which provides Babel’s translation API. Babel /preset-env includes: ES2017, ES1016, ES2015 and other common plug-in presets. Other plugins can be optionally installed and added in the.babelrc file
cnpm i @babel/core babel-loader @babel/preset-env -D
{ test: /\.jsx? $/, exclude: [resolve('../node_modules')], use: [ { loader: 'babel-loader', options: { cacheDirectory: true } } ] }Copy the code
Example of the.babelrc file configuration:
{
"presets": [
"@babel/preset-env"
],
"plugins": [
[
"@babel/plugin-transform-runtime",
{
"corejs": 2
}
],
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
],
"@babel/plugin-proposal-optional-chaining"
]
}
Copy the code
Working with CSS files
Installing related Loaders
Postcss-loader aotoprefixer is used to add CSS browser prefixes to resolve compatibility problems. You also need to configure the postcss.config.js file. Development environments use style-loader to run faster, while production environments use mini-CSS-extract-plugin to extract CSS files with better performance. Configuration is as follows
cnpm i css-loader less less-loader style-loader postcss-loader aotoprefixer mini-css-extract-plugin sass-resources-loader -D { test: /\.(css|less)$/, exclude: [resolve('../node_modules')], use: [ devMode ? 'style-loader' : MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'less-loader', { loader: 'sass - resources - loader', / / style of extract the public variable to the global options: {resources: [resolve ('.. / SRC/assets/styles/common. Less ')]}},Copy the code
Example for configuring the postcss.config.js file
module.exports = {
plugins: [
require('autoprefixer')
]
}
Copy the code
Handle images, fonts and other files
No longer need to install url-loader, file-loader
{test: / \. (PNG | JPG jpeg | | SVG | GIF) $/, type: 'asset/inline / / export a data resource URI. This was previously implemented using urL-loader. }, { test: /\.(ttf|otf|woff2? | eot) $/, type: 'asset/resource', / / export a single file, by using the file - loader before implementation. Generator: {filename: 'fonts/[name][ext]' //Copy the code
- plugins
Use to customize the WebPack build process in various ways. Webpack comes with a variety of built-in plug-ins, or you can install them yourself on demand. The following are only a few examples:
CNPM I friendly-errors-webpack-plugin node-notifier -d: CNPM I friendly-errors-webpack-plugin node-notifier -d
Install the visualization plug-in for packaged project analysis: CNPM I webpack-bundle-Analyzer -d
const webpack = require('webpack') const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') const MiniCssExtractPlugin = require('mini-css-extract-plugin') const { VueLoaderPlugin } = require('vue-loader') const CopyWebpackPlugin = require('copy-webpack-plugin') const CompressionWebpackPlugin = require('compression-webpack-plugin') const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin') const notifier = require('node-notifier') const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer') plugins: [new VueLoaderPlugin(), // Install vue-loader vue-template-compiler new HtmlWebpackPlugin({// Generate HTML template: resolve('../public/index.html'), favicon: Resolve ('../public/lyf.jpg')}), new MiniCssExtractPlugin({// extract CSS into a separate file filename: 'css/[name].css' }), new webpack.ProgressPlugin(), New CopyWebpackPlugin({// Copy resources that do not need to be built to the packaged dist directory Patterns: [{from: resolve('../src/statics/dependences'), to: Resolve ('../dist/dependences')}]}), new CompressionWebpackPlugin({// enable gzip: / \. (js | CSS) $/,}), new webpack. HotModuleReplacementPlugin () / / configure hot update plug-in new FriendlyErrorsWebpackPlugin ({onErrors: (severity, errors) => { if (severity !== 'error') { return } const error = errors[0] notifier.notify({ title: "Webpack error", message: severity + ': ' + error.name, subtitle: error.file || '' }) } }), new BundleAnalyzerPlugin({ analyzerMode: 'disabled', generateStatsFile: true, }) ]Copy the code
- mode
Provides the mode configuration option to tell Webpack to use the built-in optimization for the corresponding mode in the development environment: Development
Production environment: Production. If not, Webpack sets the default value of mode to Production
- resolve
Configuration options set how modules are parsed, such as extensions and alias. In addition, V5 removes the automatic import of Node built-in modules. Pages that use related modules need to import and install this dependency in resolve.fallback, for example: path
Resolve: {extensions: ['.vue', '.js', '.less'], // Resolve: {extensions: ['.vue', '.js', '.less'], // Resolve: {extensions: ['. Path: require.resolve('path-browserify')}}Copy the code
-
stats
Stats: {// Preset: ‘minimal’, // Preset builtAt: true, errorDetails: true, moduleTrace: true},
-
devServer
Develop a server to use and provide a local service
DevServer: {host: 'localhost', port: 8080, open: true, hot: true, // Enable webPack HotModuleReplacement HistoryApiFallback: true, contentBase: resolve('.. /dist'), // service file path proxy: {// configure related proxy '/ API ': {target: 'http://localhost:8080', Secure: false, changeOrigin: true, pathRewrite: { '^/api': '' } } }, },Copy the code
- optimization
Optimize and compress CSS, HTML, and JS files for production environments. Add this plugin to optimization.minimizer
cnpm i html-minimizer-webpack-plugin css-minimizer-webpack-plugin terser-webpack-plugin -D optimization: { minimize: true, minimizer: [new HtmlMinimizerPlugin(), // Compress HTML new CssMinimizerPlugin(), // // compress CSS new TerserWebpackPlugin({// compress JS parallel: true, extractComments: false, terserOptions: {compress: {drop_console: true, // Remove console drop_debugger: true // Remove debugger}, format: {comments: False // remove comments}}})], splitChunks: {chunks: 'all', // this indicates which chunks will be selected for optimization. Name: 'chunks' // Name of the chunks to be split}},Copy the code
- devtool
Does this option control whether and how the Source map is generated
Eval-cheap-module-source-map is recommended for development environments and can be omitted for production environments
- performance
Configure how to display performance prompts. The default is 250K with a warning. For example, if a CSS/JS resource exceeds 5MB, Webpack will print a warning to notify you
Performance: {hints: 'warning', // Optional values: Warning, error, false maxEntrypointSize: 5 * 1024 * 1024, // maxAssetSize: 5 * 1024 * 1024, // the unit is byte assetFilter: function (assetFilename) { return assetFilename.endsWith('.js') || assetFilename.endsWith('.css') }, },Copy the code
- externals
A method to “exclude dependencies from the output bundle” is provided, which prevents importing packages into the bundle and instead fetches these extended dependencies externally at runtime. You can greatly optimize the size of compressed and packaged files to improve page response times
The configuration is as follows: Key is the package name imported from the page, and value is the global variable thrown by the third-party package
Externals: {// Write everything that needs to be ignored inside the index.html file, but only if script introduces 'vue': 'vue', 'vue-router': 'VueRouter', 'vuex': 'Vuex', 'axios': 'axios', 'lodash': '_', 'element-ui': 'ELEMENT', }Copy the code
In general, externals is configured so that the import lodash from ‘lodash’ code can be interpreted in any environment without introducing Lodash itself.
Webpak5 compares the changes to version 4.0
-
Webpack 5 has removed the automatic introduction of polyfill for the NodeJS core module, so manual introduction is required. If the nodeJS core module is used in the file during the packaging process, WebPack will prompt you to configure it accordingly. Fallback: path: require.resolve(‘path-browserify’) and install the dependency package path-browserify
-
No longer need the clean-webpack-plugin to clean up the packaged dist directory, just add: clean:true to the output property
-
Removed file-loader, url-loader, and replaced it with asset Module
-
The hash value of the output filename is deprecated and can be replaced by contenthash. Webpack V5 fixes the CSS hot update problem, but using the mini-CSs-extract-Plugin to set filename cannot have a hash value, otherwise the output file will not be found. Hot update is normal without contenthash value, and no error will be reported.
-
After the webpack-dev-server service is installed, the project startup command is changed to webpack serve
-
Const {merge} = require(‘webpack-merge’) {merge} = require(‘webpack-merge’)
-
The built-in webPack method NamedChunksPlugin has been removed. No configuration is required. The console displays the relative path of the module by default when using hot updates
-
The CSS minimizer-webpack-plugin can be used instead of the mini-CSS-Assets-webpack-plugin. It is more accurate than using query strings in Source Maps and Assets, and supports caching and concurrent mode. Add use to optimization.minimizer
cnpm i css-minimizer-webpack-plugin html-minimizer-webpack-plugin -D new HtmlMinimizerPlugin() new CssMinimizerPlugin() Copy the code
-
Uglifyjs-webpack-plugin is no longer used for compression of JS files in production environment. This plugin does not support compression of ES6 syntax. The latest Terser-webpack-plugin comes with WebPack V5 and needs to be installed separately if the internal configuration needs to be modified.
cnpm i terser-webpack-plugin -D new TerserWebpackPlugin() Copy the code