Webpack 4.0 configuration learning improved
What is Webpack?
In essence,webpackModule Bundler is a static module bundler for modern JavaScript applications. whenwebpackWhen working with an application, it recursively builds a Dependency graph containing each module the application needs, and then packages all of those modules into one or more bundles (as cited on the WebPack website).
Personally understand, in the more and more engineering nowadays, in addition to writing interface and functions, the front-end also needs to reasonably manage some modules and resources required by the front-end, such as JS compression, CSS compression, syntax formatting, cache, compatibility and so on. However, different industries and businesses have different front-end requirements, as well as different code compilation, compression and performance requirements. Therefore, we need to match our own projects for different projects, so it is necessary to learn WebPack.
Two, installation environment
To run Webpack, you need to install Node.js.Node.js
- After the installation is complete, enter the following two commands on the CLI. If the version number is displayed, the installation is successful.
node -v
npm -v
Copy the code
- Execute NPM init to initialize the project, and a package.json file is generated when complete
npm init
Copy the code
- In order to improve the installation speed, it is recommended to install taobao NPM image
/ / by the following code to complete the installation of the CNPM NPM install - g CNPM - registry=https://registry.npm.taobao.org / / the following installation for webpack CNPM install - D webpack cnpm install -D webpack-cliCopy the code
- Create a new webpack.config.js file in the package.json sibling directory
- Webpack.config. js is the webpack configuration file and is executed according to the configuration
- All build tools run on Node and modularity defaults to common.js
Detailed configuration of Webpack
The following is the complete configuration
const { resolve } = require('path')
const HtmlWbbpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/js/index.js',
output: {
filename: 'build.js',
path: resolve(__dirname,'build')
},
module:{
rules:[
{
test:/\.css$/, use:[// create the style tag, put the style in the interface //'style-loader', / / the loader to replace styleloader, extract the CSS in the js files into a separate file MiniCssExtractPlugin. Loader, / / to integrate the CSS file and js file'css-loader'
]
}
]
},
plugins:[
new HtmlWbbpackPlugin({
template: './src/index.html'
})
],
mode:'development'// DevServer, auto-compile, auto-open browser, auto-refresh // features will only be packaged in memory, Devserver :{contentBase:resolve(__dirname,'build'),
compress:true,
port:3000,
open:true// Enable the HMR function, modify the configuration and restart the service hot:true}}Copy the code
-
The entry (entry point) indicates which module WebPack should use as a starting point for building its internal dependency graph. Once inside the entry start point, WebPack finds out which modules and libraries are (directly and indirectly) dependent on the entry start point: Entry entry start type
- String –> single entry ‘./ SRC /js/index.js package into a chunk and output a bundle file
- For example, the package generates build.js
-
Array –> multiple entries, resulting in only one chunk and only one bundle output
entry: [ './src/add.js'.'./src/index.js',].Copy the code
-
Object –> There are several entry files to form several chunks and output several bundles. In this case, chunkname is the key, which is suitable for multi-page programs to package their OWN JS and HTML respectively
entry: { add:'./src/add.js', index:'./src/index.js',},Copy the code
- String –> single entry ‘./ SRC /js/index.js package into a chunk and output a bundle file
-
output:
output: { filename: '[name].js', path: resolve(__dirname,'build'), publicPath:'/' , chunkFilename: '[name]_chunk.js', library:'[name]', libraryTarget:'window',},Copy the code
- Filename indicates the output filename
- Path Indicates the output path. _dirname indicates the absolute path of the current file directory. Resolve indicates the method of concatenating absolute paths
- PublicPath publicPath imported by all resources
- ChunkFilename Non-entry chunkJS
- Library Specifies the name of a variable that is exposed to the entire library
- LibraryTarget variable name added to that property window in browser, global for node
-
Loader Webpack itself can only recognize JS and JSON class files. You need to use some tools to convert the source code of the module. You can convert files from different languages (such as TypeScript) to JavaScript or convert inline images to data urls. Loader, like a translator, can convert original files to produce new results, and a file can be chained through multiple files for conversion. Therefore, the Loader function is a transform, which is essentially a function:
- Loaders must be installed to identify different types of files
// Install css-loader --save-dev css-loader // load TypeScript to js NPM install --save-dev ts-loaderCopy the code
- use
// Detailed configuration module: {rules: [// Detailed loader configuration {//testRepresents which files to matchtest: /\.css$/, // Which loader to use, execute order from right to left: [// create style tag, insert js style resource, add to head effect'style-loader'// Load the CSS file as a common.js module into our js'css-loader'}, {//testRepresents which files to matchtest: /\. Less $/, // Which loaders to use from right to left use: ['style-loader'.'css-loader'.'less-loader',]}]},Copy the code
- Loaders must be installed to identify different types of files
-
Plugin solves other functions that loader cannot implement and plugin is used to enhance webPack functionality. Webpack is made more flexible by the plugin mechanism to adapt to different development scenarios. Plugin is essentially a class that can be called multiple times during the webPack lifecycle:
``` const { resolve } = require('path') const HtmlWbbpackPlugin = require('html-webpack-plugin') module.exports = { entry: './src/index.js', output: { filename: 'build.js', path: resolve(__dirname,'build') }, module:{ rules:[ ] }, plugins:[ new HtmlWbbpackPlugin({ template: './src/index.html' }) ], mode:'development' } ``` Copy the code
- The html-webpack-plugin creates an HTML file by default and introduces packaged output of all resources
- Mode of use
cnpm install html-webpack-plugin
Install, and thenConst HtmlWbbpackPlugin = require('html-webpack-plugin')
Finally, new comes out in the plugin class. Plugin is essentially a class, so new must come out
-
mode:
- Code set to development output will not be compressed
- Code set to production output is compressed and hard to read
- Code set to development output will not be compressed