Webpack can do:
- Handle all kinds of resources, CSS, JS, HTML, images, etc
- Code conversion, file optimization, code segmentation, module combination, automatic refresh, code verification, automatic release
1. Basic use
1. Install
The webpack4 version is used here
npm install --save-dev webpack webpack-cli
Copy the code
2. 0 configuration
The default entry is index.js under SRC and the exit is main.js under dist
The webpack4 version is silently packaged with the production environment and files are compressed after packaging
// Run NPX webpackCopy the code
3. Configure it manually
The default configuration file name is webpack.config.js. Webpack is written in Node, so the configuration file uses node’s modular syntax
Module. exports = {entry: './ SRC /index.js', output: {filename: 'build.js', //' path ': Path. resolve(__dirname, 'dist'), //' publicPath: '}, mode: Development, // There are two default modes, one is the production environment, the other is the test environment development}Copy the code
1. Entrance and exit
- Entry file here is the single file, which is the entry to the project
- Output Export file configuration, including name, input location, publicPath(package file added path, usually domain name for CDN)
The resolve configuration tells Webpack how to find the corresponding file of the module
-
The alias attribute is used to define an alias, and can be used without having to use a long path, such as the ‘SRC /components’ path if the page starts with components
import button from 'components/button' import button from '/src/components/button' resolve: { alias: { 'components': '/src/components' }} Copy the code
-
The Extensions project often introduces files without suffixes for simplicity, and webPack automatically suffixes them to check if the file exists
Import button from 'components/button' // ['. Js', 'vue', 'json'] / / in turn according to the js, vue, json add final syllable and then find the fileCopy the code
-
Modules Modules tells WebPack which directories to look for third-party modules. The default is node_modules, and I usually configure my own module library
modules: ['./src/components', 'node_modules'] Copy the code
-
MainFields has files that provide several pieces of code for different environments, such as ES5 and ES6, with entries written in the package.json library file
{ "next: main": 'es/index.js', // ES6 "main": 'lib/index.js' // ES5 } Copy the code
For example, if we want to load ES6 first, this configuration is required
mainFields: ["next: main", "main"] Copy the code
4. Customize the config file name
Use the config parameter to locate the configuration file
// Run NPX webpack --config webpack.config.test.js //Copy the code
Or configure it directly into package.json
scripts: {
'build': 'webpack --config webpack.config.test.js'
}
Copy the code
run
npm run build
Copy the code
2. Webpack-dev-server Web server
1. Install
npm install --save-dev webpack-dev-server
Copy the code
2. Start the dev server. –
npx webpack-dev-server
Copy the code
3. Port 8080 is a static server
But static directories are not what we need. What we need is to start a local server that packages files into memory
4. DevServer configuration
{devServer: {host: '127.0.0.1', port: 9999, contentBase: './build'}}Copy the code
The default is localhost, but the service will not succeed unless 127.0.0.1 is set to 127.0.0.1. After the service is started, it will find the HTML file under contentBase
5. The agent
Start a 3000 web service locally, but the interface is on another server, such as port 4000, and then proxy the interface to the interface server
devServer: {
proxy: {
'/api/': 'http://localhost:4000'
}
}
Copy the code
If port 3000 accesses a resource with an API, port 4000 will delegate it to port 3000
3. Commonly used the plugin
1.html-webpack-plugin
You can copy a template to the packaged directory and insert the packaged JS into the template without having to add HTML files
Plugins: [new HtmlWebpackPlugin({template: 'template file path ', filename:' generated filename '})]Copy the code
You can also compress the generated HTML
New HtmlWebpackPlugin({minify: {collapseWhitespace: true, // delete space}})Copy the code
2. clean-webpack-plugin
The main purpose is to delete the target file after packaging, and then packaging,
let { CleanWebpackPlugin } = require('clean-webpack-plugin')
new CleanWebpackPlugin({
root: path.resolve(__dirname, 'build')
})
Copy the code
3. copy-webpack-plugin
The main purpose is to copy some static resources into a packaged directory
Let CopyWebpackPlugin = require('copy-webpack-plugin') new CopyWebpackPlugin([{from: 'static file ', to:' pack '])Copy the code
4. DefinePlugin
This is a plug-in that comes with WebPack and is used to define variables, primarily to distinguish between production and Dev environments
New webpack.defineplugin ({"process.env": {'NODE_ENV': 'development' // This assignment can be development or production}})Copy the code
Process. env is used directly to distinguish the environment
process.env.NODE_ENV == 'development'
Copy the code
4. Commonly used loader
Let’s see which loaders can handle these resources: CSS, JS, global variables, and files
1. css-loader
Css-loader is used to parse @import and URL when we import a CSS file in index.js
// index.js
import css from './style.css'
console.log(css)
// style.css
body{
background: red;
}
Copy the code
Webpack loader configuration, all loader rules are written in the Module object rules, rules object is an array, receive multiple rules, rule parsing from back to front
module: {
rules: [
{ test: /\.css$/, use: ['css-loader']}
]
}
Copy the code
Start the dev-server service and see that the CSS in index.js is parsed as an array. The first element is the path and the parsed style string
Css-loader only loads CSS modules into JS code
2. style-loader
This will parse the CSS, but the page has not yet taken effect, that is, the CSS has not been parsed into the page, in this case needs to style-loader, style-loader will generate CSS array style, After parsing, a style tag is generated and inserted into the head so that the style takes effect
Loader name: use: [‘style-loader’, ‘css-loader’], all rules are from right to left
module: {
rules: [
{ test: /\.css/, use: [ {loader: 'style-loader'}, {loader: 'css-loader'} ]}
]
}
Copy the code
At this point in the page you have a style in the head
3. less-loader
The main function is to convert less syntax into CSS syntax, need to install less-loader and less module, less-loader will call the render method of less, which will be mentioned later in handwriting
rules: [
{ test: /\.less$/, use: [ 'style-loader', 'css-loader', 'less-loader' ]}
]
Copy the code
4. postcss-loader
In the old days of browser compatibility, different prefixes were added to different browsers, which led to several compatible code being written
We can understand it as a compilation tool for CSS, similar to Babel on JS processing, it provides CSS parser, CSS parsing into abstract syntax number (AST), although the CSS itself will not deal with anything, but through plug-ins can be implemented on CSS operations,
Common autoprefixer, cSS3 code completion
Postcss-loader: PostCSS is used before CSS (from right to left)
module: {
rules: [
{ test: /\.css$/, use: ['style-loader', 'css-loader', 'postcss-loader']}
]
}
Copy the code
Add a postcss.config.js as well
var autoprefixer = require('autoprefixer')
module.exports = {
plugins: [ autoprefixer ]
}
Copy the code
Add a transform: rotate(45deg) to the element and you’ll see the added prefix
5. babel-loader
Babel does not escape code. If there is no plug-in, the code will not change after Babel processes it
The installation
Install babel-loader @babel/core @babel/preset-env
module: {
rules: [
{ test: /\.js$/, loader: 'babel-loader'}
]
}
Copy the code
To add the imported plugin file.babelrc, where the escape rules can be configured as needed,
I used to use stage-2,
There are also plugins such as transform-Runtime (generator syntax),
There are also instances where methods such as array includes can be used with babel-Polyfill
{
persets: ['@babel/preset-env']}
Copy the code
6. expose-loader
In order to solve the problem that some plug-ins do not support CommonJs, such as bootstrap.js, only jquery can expose global variables, so there will be a need to expose third-party libraries as global variables
First of all, webPack configuration, here to note, no version written differently, support webPack is also different
rules: {
test: require.resolve('jquery'),
loader: 'expose-loader',
exposes: ['$', 'jQuery']
}
Copy the code
$and jQuery will be mounted under the window when require is used in the file
require('jquery')
Copy the code
There are other ways to expose global variables, such as webpack externals and Webpack ProvidePlugin. Jquery can be used to expose global variables directly without requiring it
7. file-loader
Mainly deal with some imported resources, pictures, fonts, ICONS, etc., package the processed pictures into the corresponding directory below
rules: [
{ test: /\.(png|jpg\gif)$/, loader: 'file-loader' }
]
Copy the code
In this case, the packaged file directory will have an image resource with a hash prefix
8. url-loader
Different from file-loader, base64 is generated directly for small size images, so that the page does not need to request image resources, and directly loads the images. However, base64 is generally larger than the images before packaging. If the limit exceeds k, file-loader will be used to package the image. If the limit is smaller than k, url-loader will be used to generate base 64
rules: [
{ test: /\.(png|jpg|gif)$/, loader: 'url-loader', options: {
limit: 200 * 1024
}}
]
Copy the code
5.Source Map
When the formal environment is packaged, the code will be compressed, and the code may be displayed in a line. When an error is reported in the code, the source map is mapped because the specific location of the error cannot be found in a line, which is more conducive to debugging
Module. exports = {devtool: 'config'}Copy the code
The following are the results of different configuration items
- Source-map: source code mapping, the most complete function, packaging speed will be slow, will generate a separate. Map file
- Eval-source-map: directly writes source-map to the source code, which does not affect the build speed, but only affects the execution speed
- Cheap -module-source-map: creates a separate map file without the map, which the developer can see does not correspond to the corresponding column
- Cheap-module-eval-source-map: The map file is not generated separately, but the developer tool can see rows, not columns
End of 6.
This article mainly introduces webpack some commonly used plug-ins and usage, followed by optimization and handwriting loader and plugin and source code implementation of the article, tepid update…. , welcome to follow