preface
Nowadays, webpack has become the core of development no matter in the project development at work or in their own private projects. It is essential for almost all front-end developers to understand WebPack.
However, the official webpack document is more difficult for beginners to learn Webpack, because of the powerful webpack function, has a certain complexity, the document is also difficult to do everything.
Below I will make a summary of my own learning webpack, which can be said to be a beginner’s guide, hoping to give more people who want to learn Webpack a guide to understand Webpack.
This chapter will walk you through setting up a basic front-end development environment and then go through the basic common configurations of WebPack
This article is not limited to the first level, but has been updated to the WebPack optimization front end project at GITHUB: github.com/Jason9708/w… If I can help you learn webpack, I hope I can give you a thumbs up (I have an ideal to be an excellent writer of nuggets).
Basic concepts of Webpack
Webpack is essentially a packaging tool that helps us package code from multiple modules by resolving module dependencies based on the content of the code.
Webpack packs multiple code modules (which can be of different file types) used in our project into a few static files that the project only needs to run. Webpack has a very rich set of configuration items and provides very powerful extensibility capabilities to do a lot of things during the packaging build process.
Entrance (Enrty)
There is a JS file in each code module that acts as an entry point to the WebPack build. Webpack reads this file, resolves dependencies from it, and then packages. (The default entry file is./ SRC /index.js)
Depending on the needs of the project, it may be a single page application or a multi-page application. If it is a single page application, there is only one entry. If the project is a large, multi-page application, there will usually be multiple entries, one for each page
The following is an example of a configuration entry
// module. Exports = {entry:'./src/index.js'} // exportmodule. exports = {entry: {application1:'./src/application1.js',
application2: './src/application2.js', / /... Module. exports = {entry: {main: ['./src/application1.js'.'./ SRC /application2.js]}} // In this last example, which can be interpreted as multiple files as a single entry, WebPack resolves the dependencies of the two files and packages themCopy the code
Loader
Webpack provides a mechanism for handling multiple file formats through the Loader. Loader can be thought of as a converter that converts the content of a certain file format into packaged modules that WebPack can support
Ps: Webpack packs all dependencies into JS files by default without adding additional plug-ins. If the entry file relies on a.hbs template file and a.css style file, then handlebars-loader is required to handle the.hbs file. You need csS-loader,style-loader to process.css files, and finally parse files of different formats into JS code, so that they can be packaged and run in the browser.
How to configure loader regulations? When we need to use different loaders to parse different types of files, configure the rules under module.rules
Use Babel to handle the.js file module: {//... rules: [ {test:/\.jsx? /, / /testA regular expression that matches a file path usually matches the file type suffix include: [path.resolve(__dirname,'src') // Specify the path where the loader processes files.'babel-loader', // specify the loader to use}]}Copy the code
Loader supports the function of Webpack to process files, so it is more important and complicated. If you want to play Webpack well, you must play Loader well
Plugin
In the WebPack build process, plugin is used to handle more of the other build tasks (module code conversion is handled by Loader, and anything else can be done by Plugin). We add the required plugin according to the requirements to achieve the functions we need (Such as HtmlWebpackPlugin can generate and create HTML entry files).
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
// ...
plugins: [
new HtmlWebpackPlugin
]
}
Copy the code
Plugins work throughout the WebPack build process and can customize their own build requirements at each step of the process. If necessary, we can also develop our own plugins based on WebPack to suit our needs
Output the output
The output is the static file that WebPack eventually builds. Output can be used to configure the file name, path, and so on for the build result
module.exports = {
//...
output: {
path:path.resolve(__dirname,'dist'Dist filename:'index.js'Module.exports = {entry: {application1:} // Exports = {entry: {application1:'./src/application1.js',
application2: './src/application2.js',
},
output: {
filename: '[name].js',
path: __dirname + '/dist',}}Copy the code
❗ If not configured, the output is created by default./dist/main.js
A simple WebPack configuration
❗ webpack
The runtime defaults to read under the projectwebpack-config.js
So let’s create one manuallywebpack.config.js
file
The configuration of WebPack is actually a Node.js script that exposes a configuration object through which WebPack reads the relevant configuration. Because it’s a Node.js script, it’s very playable, and you can use any Node.js module, such as the Path module, or a third party module.
const path = require('path')
const UglifyPlugin = require('uglifyjs-webpack-plugin'Module.exports = {entry:'./src/index.js'// output: {path: path.resolve(__dirname,'dist'),
filename: 'output.js'
},
module: {
rules: [{
test: /\.jsx/,
include: [
path.resolve(__dirname, 'src')
],
use: 'babel-loader'Resolve: {modules: [resolve: {modules: ["node_modules",
path.resolve(__dirname, 'src')
],
extensions: [".wasm".".mjs".".js".".json".",jsx"], }, plugins: [new UglifyPlugin() // Use uglifyjs-webpack-plugin to compress JS code // If you notice the results of our initial build directly using webpack, This is also the effect of our --mode production command. The mode parameter for webpack will be described in a later section.]}Copy the code
The front-end community three frameworks are based on webPack scaffolding tools
- create-react-app
- angular/devkit/build-webpack
- vue/cli
Build a basic front-end development environment
Basic front-end development environment requirements analysis
- Build the HTML,JS, and CSS files we need to publish
- Use CSS preprocessors to write styles
- Process and compress images
- Support ES6 syntax with Babel
- Static services are provided locally to facilitate modality development
HTML
Typically, a front-end project starts with a page (that is, HTML). The easiest way to do this is to create an.html file and use script references to build.js files
<script src="./dist/output.js"></script>
Copy the code
If our file name or path changes, such as using [hash] for naming, it is better to associate the HTML reference path with our build result and use the html-webpack-plugin
The HTml-webpack-plugin is a standalone dependency package, so install it before using it.
npm install html-webpack-plugin -D
Copy the code
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
// ...
plugins: [
new HtmlWebpackPlugin
]
}
Copy the code
After this configuration, the html-webpack-plugin will create an.html file for us at construct time, which will reference the constructed HTMl-webpack-plugin and pass in a written.html template
module.exports = {
// ...
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html'Template: path.join(__dirname,'./src/index.html'), // Specify template page}),],}Copy the code
Css
When we want to use Webpack to build the CSS we wrote, we need to introduce related loaders in the configuration to parse and process. CSS files (style-loader and CSS-loader are required, both of which are dependent packages and need to be installed first).
module.exports = {
rules: [
{
test: /\.css/,
include: [
path.resolve(__dirname,'src')
],
use:[
'style-loader'.'css-loader']]}}Copy the code
css-loader,style-loader
The role of
- Css-loader: is responsible for parsing CSS code and handling CSS dependencies, for example
@import
As well asurl()
A declaration that references external files - Style – loader: will
css-loader
The result of parsing is converted to zerojs
Code that is inserted at run time into<style></style>
To get incss
The code works
After csS-loader,style-loader processing, CSS code will be converted into JS code, and finally packaged together.
To separate the.css file, use the extract-text-webpack-plugin (which is not explained here).
const ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = {
// ...
module: {
rules: [
{
test: / \. CSS $/, / / because this plug-in need to interfere in the content of the module conversion, so you need to use its corresponding loader use: ExtractTextPlugin. Extract ({fallback:'style-loader',
use: 'css-loader',}})],}, plugins: [/ / introducing the plug-in, profile name, here also can use [hash]
new ExtractTextPlugin('index.css'),],}Copy the code
Css Preprocessor (Less/Sass)
Less/Sass is indispensable in work. Webpack can configure loader to support Less/Sass operation
For example, use Less as an example to configure the CSS loader, style-loader, and less-loader. DOM module.exports = {// exports... module: { rules: [ {test: /\.less$/,
use: [{
loader: 'style-loader'
}, {
loader: 'css-loader'
}, {
loader: 'less-loader'}]}}Copy the code
We can also modify the webpack configuration module.exports = {//... module: { rules: [ {test: / \. Less $/, / / because this plug-in need to interfere in the content of the module conversion, so you need to use its corresponding loader use: ExtractTextPlugin. Extract ({fallback:'style-loader',
use: [
'css-loader'.'less-loader',],}),},],}, //... }Copy the code
Working with image files
Images are absolutely necessary in the front end workflow, although we have dealt with url() reference file paths in CSS-Loader style resolution, webPack can’t handle JPG/PNG/GIF file formats, so we need to add a Loader configuration to allow us to use image files
File-loader can be used to process many types of files. It mainly outputs files and returns the built file path.
Configure file-loader and add the configuration for parsing image files in Rules
module.exports = {
// ...
modules: {
// ...
rules: [
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {},
},
],
}
]
}
}
Copy the code
PS: There is also a loader to handle, that is, url-loader
Babel handles ES6 and ES7 standards
Babel is a JS compilation tool that allows us to use the new ES features. We can configure Babel in Webpack and let us write JS code in ES6 and ES7 standards
module.exports = {
// ...
module: {
rules: [
{
test: /\.jsx? // Support js and JSX include: [path.resolve(__dirname,'src'), // SRC directory is processed by babel-loader.], loader:'babel-loader',},],},}Copy the code
We need to create a.babelrc file in the root directory to configure Babel
Start static services
To enable static services, you can use webpack-dev-server to enable a simple static service locally for development
Install webpack-dev-server and configure package.json
"scripts": {
"build": "webpack --mode production"."start": "webpack-dev-server --mode development"
}
Copy the code
Run the project using NPM run start, visit http://localhost:8080/ (the default is index.html)
To end the run, press CTRL + C
How does WebPack resolve the code module path
The front-end working specification for modular development is well established, and in modularity supported by WebPack, we can use import XXX from ‘xxx.js
For example, when we use VUE for development, we must use import VUE from ‘VUE’. When webpack is built, it will parse the dependency and then load the module file of the dependency
So how does Webpack parse xxx.js or Vue into a module file path ❓
Module resolution rules
- Resolving the relative path
- Find if there are files or folders in the path relative to the current module
- If it is a file, load it directly
- If it is a folder, continue to look under the folder
package.json
- There are
package.json
The files follow the filesmain
Field filename to find the file - If there is no
package.json
Or nomain
Field, is searched by defaultindex.js
- Resolving module names
- Find files in the current file directory, parent directory and above directory
node_modules
Folder to see if there is a module with the corresponding name
- Find files in the current file directory, parent directory and above directory
- Analytic absolute path
- Directly find the file in the corresponding path
In Webpack, configuration related to module path resolution is in the Resolve field
module.exports = { resolve: { //... }}Copy the code
Resolve Common Configurations
- Resolve. alias Sets the alias
Let’s say we have a utils module that we use as our utility file and that we import frequently throughout the project. It would be cumbersome to import the utils module with a path every time we import it, so we can configure the alias to import ‘utils’
alias: {
utils: path.resolve(__dirname,'src/utils'Resolve and __dirname to get the absolute path}Copy the code
Aliases are configured using fuzzy matching, meaning that utils are replaced whenever they are carried in the module
import 'utils/form.js'// this is equivalent to importing'src/utils/form.js'
Copy the code
To use exact matching, add $after the alias
alias: {
utils$: path.resolve(__dirname,'src/utils'Resolve and __dirname to get the absolute path}Copy the code
resolve.extensions
The effect of this configuration is related to the file name extension. We can use it to define that webpack itself tries to complete the suffix name for lookup during module path resolution
For example, there is a common.js file in the utils directory above, which you can refer to like this
import * as common from './src/utils/common'
Copy the code
Webpack will try to append the extensions field to the path you depend on and then start looking for any SRC /utils/common.js files that can be hit by the dependency path
❗ But if you reference common.css from SRC /style and you import ‘./ SRC /style/common, Webpack will report that it cannot parse the module
Solution: – Add the suffix – Add the. CSS configuration in the Extensions field
resolve.modules
For modules that declare dependencies directly (the Vue above), Webpack does a path search similar to Node.js, searching the node_modules directory, which is configured using the resolve.modules field
resolve: {
modules:['node_modules'], (the default is node_modules)}Copy the code
Tip: Normally we don’t tweak this configuration, but if we can be sure that all third-party dependencies in a project are in node_modules at the root of the project, then we can configure a certain absolute path before node_modules (this configuration can slightly speed up the build).
resolve: {
modules: [
path.resolve(__dirname, 'node_modules'), // specify node_modules in the current directory first. If some libraries are located elsewhere, you can add custom paths or directories'node_modules',]},Copy the code
Resolve. MainFields (use less)
It can be used to configure entry files. When referring to a module or directory, it will first check whether package.json exists, and if so, it will search for a specified file under a field, which can be configured through mainFields
Resolve: {// Target ==="web"Or target = = ="webworker"MainFields The default value is: mainFields: ['browser'.'module'.'main'], // if the target value is other, the mainFields default value is: mainFields: ["module"."main"],},Copy the code
Typically, package.json does not declare brower or module, so it looks for files in the main field
Resolve.mainfiles (use it sparingly)
When package.json is not present in the directory, we will use the index.js file of the directory by default, which can also be configured via mainFiles (but usually we do not need to modify this configuration).
Resolve: {mainFiles: ['index'] // You can add other default file names}Copy the code
Resolve. ResolveLoader (use it sparingly)
ResolveLoader is used to configure the Resolve configuration of the loader. All the original resolve configuration items are in this field
// Default config resolve: {resolveLoader: {extensions: ['.js'.'.json'],
mainFields: ['loader'.'main',}}Copy the code
The configuration provided here is relatively rare, we generally follow the standard usage mode, use the default configuration, and then install loader in the project root path node_modules.
Configure the loader
Loader matching rule
When we use loader, we add new configuration items to modules.rules, where each item is treated as a rule matching the use of Loader
Module.exports = {// exports... module: { rules: [ {test: /\.jsx? // include: [path.resolve(__dirname,'src')], // Specify the scope of the rule.'babel-loader'// rule application result} //... ] }}Copy the code
There are two key factors in rules’ matching rules: one is the matching condition, and the other is the application after the matching rule
Matching conditions are usually matched using the absolute path of the requested resource file
The official documentation defines the matching condition as resource, and the less-used issuer is the absolute path of the source file that states the dependent request
For example, import ‘./ SRC /utils.js, resource is /xx/ XXX/SRC /utils.js, and issuer is /xx/ XXX /xxxx.js. Rule conditions will try to match the two values
module.exports = {
// ...
rules: [
{
resource: {
test: /\.jsx? /, include: [ path.resolve(__dirname,'src'),],}, // If the issuer is used, the issuer is {test:... } use:'babel-loader'
}
// ...
]
}
Copy the code
Rule and condition matching
Webpack’s rules provide several configurations:
- test:... Regular matches specific conditions-include:... Match a specific path - exclude:... Exclude specific path - and: [... Must match all conditions in array - or: [...] Matches any condition in the array - not: [...] Rule out all conditions in the matching arrayCopy the code
The values of these conditions can be any of the following 5: - String must start with the supplied string, so if it is a string, we need to provide the absolute path - regular expression to determine the condition as a regular expression - Function (path) => string returnstrueRepresents a match - an array containing at least one condition - the condition that the object matches all attribute valuesCopy the code
module type
What is module type❓ module type is the concept of module type. Different module types are similar to different loaders configured, and WebPack will deal with them accordingly
Five module types
javascript/auto
: is the default type of WebPack 3 and supports various existing JS code module types — CommonJS, AMD, ESMjavascript/esm
: ECMAScript modules, not supported by other module systems such as CommonJS or AMD, are the default type for.mjs filesjavascript/dynamic
: CommonJS and AMD, excluding ESMjavascript/json
JSON data, either require or import, is the default type for.json fileswebassembly/experimental
: WebAssembly modules, currently experimental, is the default type for.wASM files
If we don’t want to use the default type, we can specify the module type with the type field when we determine the matching rule condition. For example, we can set all JS code files to use ESM type mandatory:
{
test: /\.js/,
include: [
path.resolve(__dirname,'src')].type: 'javascript/esm', // Specify the module type (default is javascript/auto)}Copy the code
Using loader configuration
rules: [
{
test: /\.less/,
use: [
'style-loader'// use string to represent loader {loader:'css-loader', options:{importLoaders: 1}}, // use objects to represent loaders.'less-loader',
options: {
noIeCompoat: true}, // pass loader configuration}]}]Copy the code
In the example above, use can be an array, a string, or an object representing a Loader.
PS: We can also use options to pass configuration items to the corresponding loader
Loader execution sequence
Multiple Loaders can be configured in a matching rule, that is, a module file can be converted by multiple Loaders. The execution sequence starts from the last configured Loader to the first configured loader. For example, in the previous example, The.less file is processed from less-loader to CSS-loader and then to style-loader, and finally becomes a packable module
The order from last configuration to first configuration is the execution scheme in the same rule, then there is another problem! When a module file matches multiple rules at the same time, in what order will loader apply it?
rules: [
{
test: /\.js$/, exclude: /node_modules/, // exclude node_modules loader:"eslint-loader"}, {test: /\.js$/, exclude: /node_modules/, // exclude node_modules loader:"babel-loader"],},Copy the code
In the example above we need to apply eslint-loader before babel-loader is applied, we cannot guarantee this order
In Rules, webpack provides a Enforce field to configure the loader type of the current rule. The default type is normal, but we can configure it as pre or Post
- The pre – pre –
- Post – rear
All loaders are executed pre -, inline -, normal -, and post, so to ensure that eslint-loader is used before babel-loader, we need to add enforce
rules:[
{
enforce: "pre", / / fronttest: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader"}]Copy the code
Using noParse
Module. noParse can be used to configure which module files do not need to be parsed.
For libraries that do not require parsing dependencies, such as jquery, you can configure them through noParse (which improves overall build speed)
module.exports = { // ... The module: {noParse: / jquery | lodash /, / / a regular expression <! -- or usefunction
noParse(content) {
return /jquery|lodash/.test(content)
}, -->
}
}
Copy the code
Use ❗noParse
Cannot be used in the module file that is ignoredimport / require / define
Equal reference mode
Configure the plugin
Plugins provide additional functionality for WebPack, and the configuration of the plugins themselves varies due to the need to provide different functionality
The Webpack plug-in is available at github.com/webpack-con… To refer to
A few common plug-ins
DefinePlugin
DefinePlugin is a built-in plug-in for Webpack. It does not need to be installed and is used directly through webpack.defineplugin
What it does: Creates global constants that can be configured at compile time and whose values can be specified in the webpack configuration
module.exports = {
// ...
plugins: [
new webpack.DefinePlugin({
_GET:JSON.stringify('get'), // const _GET = 'get'
_POST:JSON.stringify('post'), // const _POST = 'post'
_DELETE:JSON.stringify('delete'), // const _DELETE = 'delete'
_PUT:JSON.stringify('put'), // const _PUT = 'put'}})]Copy the code
These configured global constants can be used directly in your code
console.log('this Api type is' + _GET)
Copy the code
Configuration rules
- If the configured value is a string, the string is executed as a code snippet, and the result is the value of the final variable, for example
'1 + 1'
The final result will be2
- If the configured value is not a string and is not an object literal, the value is converted to a string, for example
true
Will be converted to'true'
- If an object literal is configured, then all of the objects
key
It’s going to be defined the same way
extract-text-webpack-plugin
What it does: Separate dependent CSS files into separate files
const ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = {
// ...
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loaer',
use: 'css-loader'
})
}
]
},
plugins: [
new ExtractTextPlugin('index.css') // Config file name]}Copy the code
Sometimes we build more than one entry, so the ExtractTextPlugin creates separate file plugins for each entry: [new ExtractTextPlugin('[name].css')]Copy the code
❗ Uses ExtractTextPlugin and needs to be adjustedloader
Corresponding Configuration
ProvidePlugin
ProvidePlugin is built into Webpack and is used directly through webpack.providePlugin
What it does: Refers to certain modules as variables of the program run time, without requiring import/require every time it is used
plugins: [
new webpack.ProvidePlugin({
identifier:'xxx'// Similar to import'xxx'
// identifier: ['xxx'.'xxxx'] similar to import XXXX from'xxxx'})]Copy the code
IgnorePlugin
IgnorePlugin is built into Webpack and is used directly through webpack.ignoReplugin
Function: IgnorePlugin is used to ignore specific modules so that webPack doesn’t pack them in. For example, if we use moment.js and reference them directly, there will be a lot of I18N code in the package, which we don’t need. This is how IgnorePlugin is used
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/,/moment$/)
]
Copy the code
The parameters of the IgnorePlugin
1 - matches the regular expression that introduces the module path. 2 - matches the corresponding context of the module, that is, the directory nameCopy the code
Configuration webpack – dev – server
In the development process, we should develop and run our code locally before deploying to production, which we call a local environment, which provides a simple server for accessing static files built by WebPack.
(We use it to tune code during development)
Webpack-dev-server is a tool provided by WebPack to quickly start a static service based on the current WebPack configuration.
When mode is set to Development, hot updates are available (refresh the current page based on changes in real time)
Webpack-dev-server official document
Webpack.docschina.org/configurati…
Basic use of webpack-dev-server
Webpack-dev-server is a dependency package that needs to be installed manually and used directly in the project directory that already has the WebPack configuration file
npm install webpack-dev-server -D
webpack-dev-server --mode development
Copy the code
We can also change the startup command by configuring package.json
package.json
{
// ...
"scripts": {
"dev": "webpack-dev-server --mode development"}} Then the command line can be run with NPM run devCopy the code
PS: By default, webpack-dev-server uses port 8080. If webpack has configured html-webpack-plugin to build HTML files, then we can see the index.html page when we visit http://localhost:8080. If not, webpack-dev-server generates its own page for displaying static resources
Configuration webpack – dev – server
The devServer field is the core that WebPack uses to configure Webpack-dev-server, where we can do things like change ports
DevServer configuration is commonly used
- port Specifies the port on which the static service is enabled (default: 8080) - host Specifies the host name of the static service (default: localhost) - publicPath Specifies the path to access the constructed static file in the browser (default: /) - For example have a build good file output, js, the complete access path for http://localhost:8080/output.js, if the configuration publicPath:'assets/'. Then output. Js access path is http://localhost:8080/assets/output.js - suggest production devServer. PublicPath and output. PublicPath value consistent - Proxy is used to set up the request proxy, that is, the request for a specific URL to a different server (if you need to request a separate back-end service API, this configuration can be used to proxy).'/api': {
target: "http://localhost:8000", // proxy the request with/API in the URL to http://localhost:8000 pathRewrite: {'^/api'.' '} // Remove the API part of the URL changeOrigin:true}} -contentBase is used to configure the directory that provides additional static file content, that is, to configure the access path for additional static file content (those that are not built with WebPack, But static resources are provided for access in webpack-dev-server.) Take a paw: contenBase: path.join(__dirname,"public"// Public constBase: [path.join(__dirname,"public"), path.join(__dirname, "assets")} -before & after is configured to define additional middleware in 'webpack-dev-server' - before can be used to intercept partial requests to return specific content after processing by 'webpack-dev-server' static resource middleware, Or implement a simple data mock-after that can be used to print logs after processing by the Webpack-dev-server static resource middlewareCopy the code
Configure webpack-dev-Middleware middleware
Webpack-dev-middleware is a middleware that provides webpack-dev-server static service capabilities in Express
Webpack-dev-middleware is a dependency that needs to be installed manually
NPM install webpack-dev-middleware --save-dev Const middleware = require("webpack-dev-middleware")
app.use(middleware(xxx,{
xxx
}))
Copy the code
Implement a simple mock service
In daily work, front-end staff often get stuck after page development due to incomplete back-end interface or uneven data return. Then we need mock service to help us simulate back-end data. Before or proxy configuration of Webpack-dev-server, Or webpack-dev-Middleware combined with Express can help you implement simple mock services
When we request a specific path (such as /market/shopsList), we can access the data content we want
Let’s start by implementing a simple mock functionality method based on the Express app
module.export = function mock(app) {
app.get('/market/shopsList', (req,res) => {
res.json({
data:' '})}) //... }Copy the code
Then configure the before field in webpack-dev-server
const mock= require('./mock'Before (app) {mock(app) // call mock function}Copy the code
Distinguish between development and production environments
Webpack 4.x introduces the concept of mode, specifying production or development when running WebPacks, which means we need the ability to run two sets of build environments
When you specify Production mode, various performance tuning functions are enabled by default, while development Mode enables the debug tool, which prints detailed error messages at runtime.
Break up the configuration
We can split the WebPack configuration into multiple files for different environments and load the corresponding configuration files directly at runtime based on environment variables
For example, when we build a Vue project with Webpack, i.e. vue init webpack projectName, we can see that mode has been distinguished in the Build folder
Based on this example, we can divide it into the following files
- Shared configuration - Configuration used in the webpack.dev.js development environment - Configuration used in the webpack.pro.js production environmentCopy the code
How do you handle this configuration split
The configuration of WebPack exposes a JS object, so this object can be modified using JS code
Const config = {// webpack configuration} config.plugins.push(...) Module. exports = config // exposes this objectCopy the code
We also need a tool (webpack-Merge) to merge multiple configuration objects so that we can easily split webPack configurations, determine the current environment variables, and use the tool to merge configuration objects for the corresponding environment into WebPack
To take one paw
Exports of basic shared products (webpack.base.js module.exports = {entry:... , output: { ... }, resolve: { ... }, module: { ... }, plugins: [ ... ] }Copy the code
Add loader/plugin const merge = require('webpack-merge')
const webpack = require('webpack')
const baseWebpackConfig = require('./webpack.base.js'Module. Exports = merga(baseWebpackConfig, {module: {rules: [// 注 : http://module.exports]) module. Exports = merga(baseWebpackConfig, {module: {rules: [// 注 : http://module.exports] }, plugins: [// plugins are merged with the plugins array in baseWebpackConfig...] })Copy the code
summary
So far, the general function of Webpack has had a systematic understanding, so how to be familiar with skilled use of Webpack, we need to explore from practice, according to different needs, configure suitable for the development environment and local environment of the project, in the follow-up, I will update how to optimize the project through Webpack
This article is for beginners of Webpack programmers, if you are helpful, click 👍