navigation

[Deep 01] Execution context [Deep 02] Prototype chain [Deep 03] Inheritance [Deep 04] Event loop [Deep 05] Curri Bias function [Deep 06] Function memory [Deep 07] Implicit conversions and operators [Deep 07] Browser caching mechanism (HTTP caching mechanism) [Deep 08] Front-end security [Deep 09] Deep copy [Deep 10] Debounce Throttle [Deep 10] Front-end routing [Deep 12] Front-end modularization [Deep 13] Observer mode Publish subscribe mode Bidirectional data binding [Deep 14] Canvas [Deep 15] webSocket Webpack HTTP and HTTPS CSS- Interview Handwriting Promise

[react] Hooks

[Deployment 01] Nginx [Deployment 02] Docker deployVue project [Deployment 03] gitlab-CI

[source code – Webpack01 – precompiler] AST abstract syntax tree [source code – Webpack02 – Precompiler] Tapable [source code – Webpack03] hand written webpack-compiler simple compilation process [source code] Redux React-redux01 [source] Axios [source] vuex [source -vue01] Data responsive and initialized rendering [source -vue02] Computed responsive – Initialization, access, update process

Front knowledge

Some words

It was a proposal for the decorator to expose the license and compress it, which determined the wildcard collapse. -sheldon: Extract optimization, plug, pluggable, complete, completeCopy the code

package.json

Name - Defines the name of the package, which is the name the package displays when published to the NPM registry - Must be lowercase, allowed (hyphens and underscores), not allowed (Spaces and other characters) - name: 'Webpack-learning' - Note: If you want to release to the NPM, the package name must be the only main!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Define entry point for a project. Default is index.js version. Current version of the software License. Code license. That's a one-person ficolin-3. , - "contributors" : [{" name ":"... ", "email" : "... ", "url" : "... "/"}], keywords search index - "keywords" : ["server", "osiolabs", "express", "compression"]Copy the code

Resolve and path.join and __dirName variables

  • Path.resolve () ————————— Generates the absolute path
    • path.resolve([…paths])
    • To resolve a sequence of (paths or path fragments) into (absolute paths)
    • Parameter: a sequence of paths or path fragments
    • Return value: an absolute path
    • Note:
      • If no parameter is passed, the absolute path of the current working directory is returned
      • Path fragments of length 0 are ignored
  • Path.join ()——————————— Join the path
    • path.join([…paths])
    • Note:
      • Paths of length 0 are ignored
  • __dirname — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — the current module directory name, is an absolute path

Process. The env — — — — — — — — — — — — — — — — — — — — — — — — — — — — return to contain the object of the user environment

  • Process. env returns the object containing the user environment
  • Note: The value of an attribute assigned on the process.env object is implicitly converted to a string, and an error may be reported if the value is not string, number, or Boolean
  • Note: You can modify this object, but these changes are not reflected outside the Node.js process
  • Delete property: delete
    • delete process.env.xxxx
  • Note: On Windows systems, environment variables are case insensitive
  • Process.env.node_env is not an original property of the process.env object, but is custom
    • Reason: There are differences between Windows and MAC
    • So: This is usually set by the (cross-env) plug-in
    • npm install --save-dev cross-env
    • cross-env
Process.env.foo = 'bar'; console.log(process.env.foo); (2) The process.env attribute is implicitly converted to the string process.env.test = null; console.log(process.env.test); // => 'null' process.env.test = undefined; console.log(process.env.test); // => 'undefined' (3) delete attribute process.env.test = 1; delete process.env.TEST; console.log(process.env.TEST); // => undefined (4) window (environment variable) is case insensitive process.env.test = 1; console.log(process.env.test); / / = > 1Copy the code
---
cross-env

{
  "scripts": {
    "build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"
  }
}
Copy the code

Dependencies that will be used

-webpack webpack- cli-html -webpack-plugin - webpack-dev-server CSS related - style- loader-css - Loader-less - Loader - Pull out the CSS - mini-css-extract-plugin - Prefix - postcss- Loader - autoprefixer - Compress CSS - (Note: To compress CSS for production, Because it affects packaging speed) - optimize- CSS-assets - webpack-plugin-Uglifyjs - Webpack-plugin JS related - babel-loader - @babel/core - @babel/preset-env - @babel/plugin-proposal-decorators - @babel/plugin-proposal-class-properties - @babel/plugin-transform-runtime - @babel/runtime - @babel/polyfill - eslint ellint-loader babel-eslint - expose-loader Image related - file-loader - URL - Loader - HTML -withimg-loaderCopy the code
  • 2021/01/11 update

Source warehouse

  • Webpack – Basic learning repository
  • Webpack-compiler source handwriting – source code analysis warehouse
  • Webpack-compiler source code handwritten – my nugget blog

Code split between webpack.dllPlugin and optimity.splitchunks

  • (webpack. DllPlugin, webpack. DllReferencePlugin) and optimization splitChunks can implement code segment
  • Prefer using optimization. SplitChunks. CacheGoup
  • SplitChunksPlugin
// exports = {//... Optimization: {// -------------- Default configuration, which configures effects and optimization: {splitChunks: {}} effect / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- namely splitChunks with an empty object, and the following code equivalent splitChunks: {chunks: 'async', / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- chunks: 'async' separates code only if it is imported asynchronously, such as packages or routing components that are imported dynamically with import().then() syntax // -------------- chunks: CacheGroups // -------------- chunks: 'initial' // -------------- minSize: 30000, // -------------- minSize: 30000 0, / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- maxSize said to secondary separation of library after the packaging, can match can not minChunks: MaxAsyncRequests: 5, maxInitialRequests: 3, automaticNameDelimiter: '~', // The connection between file names, such as the connection between name and the entry filename name: true, cacheGroups: {// A vendors group that may contain multiple packages: {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- said if meet chunks set items, and under the node_modules folders, Is packaged as vendors. ~ the main js / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- vendors. ~ the main said the main entrance of js file package after the file name is the main js / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- To change the name of the package to fit the configuration of chunks, use: filename to delete the configuration // ----------------- cacheGroups and chunks are used together with the test: / / \ \ / node_modules / \ \ / /, / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- introduced from node_modules folders, is actually a third-party component libraries, dependent libraries priority: -10, // --------------- priority means both the VENDORS and default are satisfied, and the higher the piroity, the higher the priority, filename: 'Vendors ', // -------------. Imported packages that satisfy chunks and all of the above criteria will be packaged into a file. vendors. Default minChunks: 2, Priority: -20, reuseExistingChunk: = default minChunks: 2, priority: -20, reuseExistingChunk: = default minChunks: 2 True, // reuseExistingChunk indicates that a package that is already packaged and referenced in another package is no longer packaged in the other package, and directly references filename: 'common'}}}}};Copy the code

Webpack basis

  • Webpack is a (module packaging) tool, the most basic is a JS module packaging tool, if you add a loader can package any corresponding resources
  • It can be configured with 0, but in order to meet project requirements, it is generally configured by itself
Operation under the zero configuration default configuration: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- NPX webpack XXX. Js generated after packaging (folder) name: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- dist generated after packaging (documents) name: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the main, js (2) the default configuration file to the default webpack webpack configuration file name: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - webpack. Config. Js | | webpackfile. Js (3) how to use the command line to specify webpack configuration file, And execute the file -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- NPX webpack - config XXXXXCopy the code

webpack webpack-cli

  • npm install -D webpack-cli webpack
  • Note that the development dependency is used online with the packaged file

webpack-dev-server

  • npm install -D webpack-dev-server
  • Webpack-dev-server can start a simple Web service with live-reloading in real time
  • Configuration items:
    • ContentBase: The directory from which the started service loads the resources
    • Port: indicates the service port number
    • PublicPath: sets the publicPath. The package files in this path can be accessed in a browser
      • For example, if it is deployed on a CDN, all imported HTML resources need to be added with the address of the CDN as the public path. In this case, publciPath needs to be set
    • Proxy: To set a proxy, use http-proxy-middleware
    • Compress: indicates whether to enable GZIP compression
    • Hot: whether to enable hot update (hot replacement of modules)
    • Open: whether to open the browser after starting the service
    • Host: Specifies the host
    • Color: Console color output, Boolean, note that only used on the command line
  • proxy
proxy var apiProxy = proxy('/api', { target: 'http://www.example.org' }); // \____/ \_____________________________/ // | | // context options (1) proxy: { '/api': Request: 'http://www.baidu.com'} '/ API/user agent will be to:' http://www.baidu.com/api/user '(2) demand: how to remove in real request path'/API solution: Proxy: {'/ API ': {target: 'http://www.baidu.com', pathRewrite: {'^/ API ': '/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- remove path or delete'/API '}}} request: '/ API/user agent will be to:' http://www.baidu.com/user 'Copy the code
Webpack - dev - server devServer: {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- webpack - dev server configuration items contentBase: Path. The join (__dirname, 'dist), / / -- -- -- -- -- -- -- -- -- -- -- -- -- start the service loading port static resources: '5000', / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- port compress: True, / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- whether to open the gzip compression open: True, / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- whether to open the browser tabs, proxy after service startup: {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- agents'/API: {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the context, need the path of the proxy target: 'http://yapi.wxb.com.cn', / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the target address pathRewrite: {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- path rewrite '^ / API: "' / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- remove path is equivalent to use 'instead of'/API '}}}},Copy the code

The proxy instance

(1) index.js const api = new XMLHttpRequest() api.open('GET', '/api/name', True) / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- request path ('/API/name) API. Onload = function () {const res = API. The response console.log(res, 'res') } api.send() (2) devServer: { contentBase: path.join(__dirname, 'dist'), port: '5000', compress: true, open: true, proxy: { '/api': { target: 'http://localhost:7000', / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the service broker to http://localhost:7000 pathRewrite: {' ^ / API: "' / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- to rewrite/API / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- '/ API/name' agent to 'http://localhost:7000/name'}}}}, (3) server => index.js var express = require('express') var app = express() app.get('/name', (req, Res) = > {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the server startup in: 'http://localhost:7000/name' res. Json ({name: 'woow_wu7' }) }) app.listen(7000, () => console.log('the server is running on port 7000'))Copy the code

html-webpack-plugin

  • npm install html-webpack-plugin -D
  • Configuration items:
    • Template: indicates the template HTML file
    • Filename: indicates the filename after the package
    • Hash: Whether to use a hash stamp when HTML references JS
    • Minify: used in mode=production, is a (Boolean) or (object)
      • RemoveAttributeQuotes: Removes the double quotes from HTML attribute values
      • CollapseWhitespace: Fold the blank line, that is, just one line of code
html-webpack-plugin const HtmlWebpackPlugin = require('html-webpack-plugin') plugins: / / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- new plugins is a plug-in array HtmlWebpackPlugin ({template: '. / SRC/index. HTML ', / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- template HTML filename: 'index.html, / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- after the packaging of the HTML file name hash: True, / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- HTML if reference js poke minify with hash: {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - compression optimization removeAttributeQuotes: True, / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- delete the HTML tag attribute value collapseWhitespace double quotation marks: True, / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- fold line empty behavior}})]Copy the code

loader

  • Loader loading order: from right to left and from bottom to top
  • Loader documentation

CSS related

( css-loader ) ( style-loader ) ( less-loader )

  • npm install style-loader css-loader less less-loader -D
  • css-loader
    • It is mainly used to support the @import syntax of CSS imports
  • style-loader
    • The main function is to embed CSS (style tag) in the HTML head tag
    • Note that the order is: after the CSS is processed by the CSS-Loader, the style-Loader is inserted into the head tag
    • Configuration options
      • Insert: ‘body’ inserts the style tag into the body tag, which is inserted into the head tag by default
< span style = "box-sizing: border-box; word-break: break-word! Important; word-break: break-word! Important;" / \. CSS $/, / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - deal with CSS / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - a regular match, pay attention to the order of the loader is from right to left, Use: [{loader: 'style-loader', options: {// insert: 'body' / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- style tags default is inserted into the header tags, here you can insert into the body tag}}, {loader: 'CSS - loader,},]}, {test: / \. Less $/, / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- with less use: [{loader: 'style - loader'}, {loader: 'CSS - loader'}, {loader: 'less-loader'} ] } ] },Copy the code

Mini-css-extract-plugin —— Extract the CSS

  • npm install mini-css-extract-plugin -D
  • By default: style-loader converts the CSS file to a style tag embedded in the HTML. We want to use the link tag to import the CSS externally, so we use the mini-css-extract-plugin to extract the CSS and import the CSS via the link tag
  • -Blair: Extract
  • The mini – CSS – extract – the plugin’s website
// ---------------- import module: {rules: [{test: : require('mini-css-extract-plugin') /\.css$/, use: [ MiniCssExtractPlugin.loader, // -------------------------------------------- loader { loader: 'css-loader', }, ] },{ test: /\.less$/, use: [ MiniCssExtractPlugin.loader, {loader: 'css-loader'}, {loader: 'less-loader'} ] } ] }, plugins: [ new MiniCssExtractPlugin({ // ---------------------------------------------------- plugin filename: '. The main CSS '/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - out of the CSS file name / / filename: 'CSS/main CSS' / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- this will generate the CSS folder after packaging, inside is all CSS in the main. The CSS file})]Copy the code

Postcss-loader and autoprefixer —— generate the browser prefix

  • postcss-loader
    • To resolve browser prefixes, compatibility handling, requires a separate configuration file, postcss.config.js
    • Solve the browser prefix :(1) configure postcss.config.js separately (2) also need to work with plug-in autoprefixer
    • Note the sequence between loaders. For example, after the less => prefix is added => identify @import => and then remove the CSS
    • Or less – loader first = > postcss – loader = > CSS – loader = > MiniCssExtractPlugin. Loader
  • autoprefixer
    • Autoprefixer needs to give some information about the browser, so add the Browserslist configuration to package.json
Postcss-loader and autoprefixer solve browser prefixes (1) Order between Loaders (2) Postcss-Loader needs to be configured separately postcss.config.js (3) Autoprefixer needs to give some information about the browser. You need to configure the browserslist property in package.json -- "browserslist" in package.json: [ "defaults", "not ie < 9", "last 3 version", ">1%", "ios 7", "Last 3 iOS versions"] -- postcss. Config.js const autoprefixer = require('autoprefixer') module.exports = {plugins: [autoprefixer]} - webpack. Config. Rules in js: [{$/ test: / \. CSS, use: [MiniCssExtractPlugin loader, {loader: 'the CSS - loader'}, {loader: 'postcss - loader'}, / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- postcss - loader, pay attention to order]}, {test: / \. Less $/, use: [ MiniCssExtractPlugin.loader, {loader: 'css-loader'}, { loader: 'postcss-loader'}, {loader: 'less-loader'} ] } ]Copy the code

The optimize- CSS-assets -webpack-plugin and uglifyjs-webpack-plugin —— compress CSS and JS

  • npm install optimize-css-assets-webpack-plugin uglifyjs-webpack-plugin -D
  • Note that the compressed CSS is only used (in production) to compress the CSS, as it will affect packaging speed
  • Note that the (HTML – webpacker -plugin) compress HTML by minify => removeAttribureQuote, collapseWhitespace is also used in the (production environment) collapse HTML
  • optimize-css-assets-webpack-plugin
    • Note:
      • Question:With the optimize- CSS-assets - webpack-Plugin, the individually extracted CSS is compressed, but the packaged JS file is not compressed
      • Solution:Use uglifyjs-webpack-plugin to solve the problem that JS is not compressed
  • uglifyjs-webpack-plugin
optimization: {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- to optimize item (optimization: is the best optimization) / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- note: Compression of CSS and JS should be seen in mode= Production. [ new OptimizeCssAssetsWebpackPlugin(), // ------ optimize-csS-assets -webpack-plugin to compress standalone CSS new UglifyjsWebpackPlugin({// ---------------- compress JS cache: SourceMap: true, // debug mapping})]}Copy the code

Js related

  • babel-loader
  • @babel/core
  • @babel/preset-env
  • @ Babel/plugin – proposal – decorators / / — — — — — — — — — — — — — — — — — — — — a decorator syntax
  • @ Babel/plugin – proposal – class – the properties / / — — — — — — — — — — — — — — the class syntax
  • @babel/plugin-transform-runtime
  • @ Babel/runtime / / — — — — — — — — — — — — — — — — — — — — — — — — — — — note is this dependence is dependencies not devDependencies
  • @babel/polyfill
  • npm install babel-loader @babel/core @babel/preset-env -D
  • npm install @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators -D
  • npm install @babel/plugin-transform-runtime -D
  • npm install @babel/runtime -SPay attention to is the -s
  • npm install @babel/polyfill -SPay attention to is the -s
  • Babel’s official website
  • Note:
    • Babel configuration:
      • (1) You can create a. Babelrc file and configure it separately
      • (2) Can be configured in the Webpack loader configuration babel-Loader options
    • @babel/plugin-proposal-decorators and @babel/plugin-proposal-class-properties
      • @ Babel/plugin – proposal – decorators — — — — — — — — — — — — — — in the former
      • @ Babel/plugin – proposal – class – the properties — — — — — — — — — in the back
Babelrc file {"presets": [["@babel/preset-env", {"modules": false}]], "plugins": [ ["@babel/plugin-proposal-decorators", {"legacy": true}], ["@babel/plugin-proposal-class-properties", {"loose": True}], ["@babel/plugin-transform-runtime"]]} ---- @babel/polyfill is imported directly into the entry js file require('@babel/polyfill')Copy the code

Added esLint validation (esLint) (eslint-Loader) (babel-eslint)

  • npm install eslint eslint-loader babel-eslint -D
  • eslint
  • eslint-loader
  • babel-eslint
  • Note:
    • (1) You need to configure the (.eslintrc.json) file separately, or you need to configure the rule rule directly in the (eslintConfig) field of the (package.json) file
    • (2) Note the order of eslint-Loader and Babel-Loader
      • Order: verify before processing
      • Yes to verify esLint-Loader first and then convert to Babel-Loader
      • With options selected in eslint-Loader, you can use enenforce: ‘pre’ to execute first, even if eslint-Loader is on top or before eslint-loader
    • Bebel-eslint Cannot find Module ‘babel-eslint’
.eslintrc {"parser": "babel-eslint", // Here "parserOptions" must be set: {"sourceType": "module", "allowImportExportEverywhere": true }, "rules": { "indent": "off", "no-console": 2 / / do not allow the console. The log ()}, "env" : {}} -- -- -- -- -- -- -- -- -- -- -- -- webpack. Config. Js {test: / \. Js $/, use: / / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the use can be an array or object {loader: 'Babel - loader, the options: {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- in addition to the configuration here, still can set alone. Babelrc file configuration Babel presets: [ ['@babel/preset-env'] ], plugins: [ ['@babel/plugin-proposal-decorators', {'legacy': true}], ['@babel/plugin-proposal-class-properties', {'loose': true}], ['@babel/plugin-transform-runtime'] ] } }, { loader: 'eslint-loader', // -------------------------- eslint-loader options: { enforce: 'pre' } } ], include: path.resolve(__dirname, 'src'), exclude: path.resolve(__dirname, 'node_modules'), }, // { // test: /\.js$/, // use: {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the use is the object / / loader: 'eslint - loader', / / options: {/ / enforce: 'pre' // }, // }, // include: path.resolve(__dirname, 'src'), // exclude: path.resolve(__dirname, 'node_modules'), // },Copy the code

The type of loader

  • Pre ———————– Pre-loader
  • Post ———————- Indicates the post loader
  • Normal ——————- Common loader
  • The inline — — — — — — — — — — — — — — — — — — — — — inline loader, which can be directly write loader in the js code

Expose – loader and wepback ProvidePlugin ()

  • npm install expose-loader -D
  • Exposing-loader Indicates a loader that exposes the global loader
  • Exposure to expose:
  • Three uses of exposion-Loader
---------------- import $from 'expose-loader? $! $($) $($) $($) $($) $($) $($) $ // require. Resolve () : // require. Resolve () : // require. Resolve () : // require. The internal require() mechanism is used to query the location of the module, which returns only the parsed file name and does not load the module. Use: [{loader: 'expose-loader', options: 'jquery'}, {loader: 'expose-loader', options: 'jquery' $}]}, (3) insert $into each module. You don't need to insert $into each module. You can use webpack.providePlugin. To add new plugins webpack. ProvidePlugin ({/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - webpack. ProvidePlugin () $: 'jquery' / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- in each module are injected $operator}) use: in the module can be used directly $, does not need to introduce of the headCopy the code

The image processing

  • npm install file-loader url-loader html-withimg-loader -D
  • file-loader
    • An image is generated into the Build directory and the name of the image is returned
  • url-loader
    • You can set the size limit. If the size limit is smaller, url-Loader will convert the image to base64. If the size limit is larger, file-Loader will load the image
    • Options: {limit: 200 * 1024}, 200K, by (limit)
    • Options: {outputPath: ‘img/’} —– Package the image into the img folder
    • Note :(1) all CSS files are separated into one file and placed in one folder using mini-css-extract-plugin (2) images are separated into one folder using options’ outputPath in url-loader
  • html-withimg-loader
    • Note: Error may be reported when using this plugin. You need to set esModule: false in the OPTIONS of url-loader
  • The way the picture is introduced
    • In js, you can use new Image().src, etc
    • In CSS, it is introduced by background-iamge
    • In HTML, it is introduced with the IMG tag
file-loader url-loader html-withimg-loader webpack.config.js { test: /\.(png|jpg|jpeg|gif)$/, use: [ { // loader: 'file-loader', loader: 'url-loader', options: { limit: 200 * 1024, // ----------------- < 200K, use base64 to encode the image, use file-loader to load the image esModule: False, / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- used for HTML - withimg - effective plugin outputPath: 'img /, / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - the output to the img folder publicPath: }}]}, {test: /\.html$/, // ----------------- html-withimg-loader use: 'html-withimg-loader'} Import one from './images/1.jpg' const imgx = new Image(100, 100) imgx.src = one if (imgx.complete) { addChild() } else { imgx.onload = addChild } function addChild() { Document. The body. The appendChild (imgx) # div - image {in} CSS width: 200 px; height: 200px; background: url('./images/1.jpg'); <img SRC ="./images/1.jpg" Alt ="" width="300" height="300">Copy the code

Static resource classification

  • The picture
    • url-loader => options => outputPath: ‘img/’
  • css
    • mini-css-extract-plugin => filename: ‘css/main.css’
  • Public path
    • Set the publicPath in output => publicPath. When HTML loads resources after packaging, the publicPath will be added
    • For example: not put in the local, put in the CDN, must be in all paths on the server address
  • If you only want to load images with a publicPath, but no other resources, you need to set it separately in the url-loader, and do not set the output publicPath
Static resource classification image {test: / \. (PNG | JPG | jpeg | GIF) $/, use: [{/ / loader: 'file - loader, loader:' url - loader 'options: {limit: 200 * 1024, esModule: false, outputPath: 'img / / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - after all the pictures will be on the packaging (img folder)}}}], CSS plugins: [ new MiniCssExtractPlugin({ filename: 'CSS/main CSS' / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- after all CSS will be placed into the package (CSS folder. The main CSS)}),], common path: all paths are add the output: { filename: 'index.[hash:8].js', path: path.resolve(__dirname, 'dist'), publicPath: 'www.baidu.com/' / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - set up the common path, packaging resources will be introduced in the HTML after add the prefix path}, common path: just pictures add {test: /\.(png|jpg|jpeg|gif)$/, use: [ { // loader: 'file-loader', loader: 'url-loader', options: { limit: 200 * 1024, esModule: false, outputPath: 'img/', publicPath: 'www.baidu.com/' / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- only to graphics Settings publicPath}}},Copy the code

Package multi-page applications

  • Entry: Can be an object
  • Output: ‘[name]. Js’ = >[] is a placeholder= >The value of [name] is the key in the entry object
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { mode: 'development', entry: { home: './src/home.js', other: './src/other.js', }, output: { filename: '[name]. Js' / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- a placeholder, said the name entry object key path: path.resolve(__dirname, 'dist') }, devServer: { contentBase: path.resolve(__dirname, 'dist'), port: 5000, open: true, compress: true, }, plugins: [new HtmlWebpackPlugin ({/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- HTML - webpack - the plugin can be more than the new template: './src/index.html', filename: 'home.html', chunks: [' home '] / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- each chunk corresponds to load what js file after the packaging, {template: './ SRC /index.html', filename: 'other.html', chunks: ['other'] }), ] }Copy the code

Source-map Indicates the source code mapping

  • devtool: 'source-map'// Display the number of lines and generate a map file
  • devtool: 'eval-source-map'// Display the number of lines without generating a map file

Watch Real-time packaging

Watch: true, watchOptions: {aggregateTimeout: 300, // Anti-shaking poll: 1000, // Check 1000 times per second /node_modules/}, aggregate, poll, aggregateCopy the code

Clean -webpack-plugin ———- Delete the folder after packaging. By default, delete the folder specified by output.paht

  • npm install --save-dev clean-webpack-plugin
  • clean-webpack-plugin
const {CleanWebpackPlugin} = require('clean-webpack-plugin') plugins: [new CleanWebpackPlugin() //---------- deletes the folder specified by output.path by default],Copy the code

Copy-webpack-plugin ———- Copies files

  • npm install copy-webpack-plugin -D
const CopyWebpackPlugin = require('copy-webpack-plugin') plugins: [ new CopyWebpackPlugin([{ from: './ SRC/copyWebPackplugin ', // -------- copy the contents of this folder to the dist folder to: '/' / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the default is output to the output. The path specified folder}])],Copy the code

BannerPlugin —————- Plugin that comes with webPack and is used to comment something at the beginning of a JS file

new webpack.BannerPlugin({ banner: 'by woow_wu7'} Webpack. ProvidePlugin ------- exposes jquery to each module and injects $into each module for the $symbol. You don't need to reintroduce jquery to each module, you can use webpack.ProvidePlugin. Add new webpack.provideplugin ({$: 'jquery'}) to pluginsCopy the code

Webpack-dev-server => before(app) => Implement mock data

devServer: { contentBase: path.join(__dirname, 'dist'), port: '5000', compress: true, open: true, // proxy: { // '/api': { // target: 'http://localhost:7000', // pathRewrite: { // '^/api': "' / / / / / /}}}, before (app) {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- before hook function, App.get ('/ API /user', (req, res) => {res.json({user: 'woow_wu7' }) }) } }, const api = new XMLHttpRequest() api.open('GET', '/api/user', True) / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- in webpack dev - sesrver bofore (app) has provided service routing / / and return data -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- so here can directly access the API. The onload = function () {const res = API. The response the console. The log (res, 'res') } api.send()Copy the code

Resolve parsing — — — — — — — — — — — — — — — — — — — — alias and extensions

  • Resolve. alias: Creates an alias for import or export
  • Resolve. extensions: Automatically resolves the determined extensions
    • Note :(resolve.extenstions) is an (array), and the member is (. Suffix string)
    • Note:Import SomeFile from "./somefile.ext". To parse correctly, a string containing "*" must be included in the array.
    • Application: Omit suffixes when importing files (priority is left to right)
Resolve.alias resolve.extensions set: resolve: {alias: {Imageff: Path.resolve (__dirname, 'SRC /images'), // use Imageff to replace the absolute path of the images folder}, extensions: ['. Js', 'CSS', 'less', '*'] / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the import omit the suffix, first find. Js file, Get. CSS file / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- note: '*'} represent all types of files, use: import imagex from 'Imageff / 1. JPG'Copy the code

Webpack.defineplugin ———- defines an environment variable, which creates a constant that can be configured globally at compile time

(1) new webpack.DefinePlugin({ // ----------------------- new webpack.DefinePlugin() DEV: JSON.stringify('DEV'), // -------------------- ( JSON.stringify('DEV') === "'DEV'" ) BOOLEAN1: true, BOOLEAN2: JSON. Stringify (true) / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- here BOOLEAN2 BOOLEAN1 equivalent}) as above, / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- so can use the JSON data. The stringify () to the operation, the incoming what type (2) what type is returned webpack plugin is often include:  new webpack.DefinePlugin({ // ----------------------- webpack.definePlugin DEV: JSON.stringify('DEV'), BOOLEAN1: true, BOOLEAN2: JSON.stringify(true) }), new webpack.ProvidePlugin({ // ---------------------- webpack.ProvidePlugin $: 'jquery' }), new webpack.BannerPlugin({ // ----------------------- webpacck.BannerPlugin banner: 'by woow_wu7' })Copy the code

Webapck-merge ———— Distinguish different environments

  • npm install webapck-merge -D
  • webpack-merge
const merge = require('webpack-merge'); // --------------- webpack-merge
const base = require('./webpack.base.js')

module.exports = merge(base, {
  mode: 'developmen',
  devServer: {
    contentBase: './dist',
    port: 8000,
    open: true,
    compress: true
  }
})
Copy the code

noParse

  • Module. noParse If the package has no other dependencies, noParse allows WebPack not to resolve the dependencies of the package to speed up the build
  • Therefore, the package cannot contain import, require, define, or any other import mechanism
  • module.noParse
Module: {noParse: / jquery | lodash /, / / -- -- -- -- -- - not to parse the jquery or lodash dependencies, because both of them are not dependent on other libraries, so as to improve the construction speed rules: []}Copy the code

webpack.IgnorePlugin

  • ResourceRegExp: regular expression matching the resource request path (test).
  • ContextRegExp :(optional) regular expression that matches (test) the resource context (directory).
  • Plugins that come with WebPack
    • Webpack.ignoreplugin --------- Ignores the introduction
    • Webpack.defineplugin --------- defines global constants
    • Webpack. ProvidePlugin-------- expose package name changed
    • Webpack. BannerPlugin--------- injects a write message string at the beginning of the js package
- webpack. Config. Js = > plugins. New webpack IgnorePlugin ({/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - from (moment) introduced in ( . / local) file, will not go to introduce. / local files in the folder / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - but you need to use the Chinese package, so ignore, introduced (manual) resourceRegExp again: /^\.\/locale$/, contextRegExp: /moment$/ }); ----- index.js import moment from 'moment' import 'moment/locale/zh-cn'; / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - manual introduced package moment. Locale (' useful - cn) const d = my moment (" 20111031 ", "YYYYMMDD").fromNow(); console.log(d, 'd')Copy the code

Webpack. DllPlugin and webpack. DllReferencePlugin — — — — — — — — dynamic link libraries, separate packing some libraries

  • Webpack. DllPlugin: => name, path
  • Webpack. DllReferencePlugin: = > the manifest
  • List the manifest:
-- -- -- -- -- - webpack. Config. React. Js / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- is dedicated to the packaging of the react and react - dom (1) the const path = require('path') const webpack = require('webpack') module.exports = { mode: 'development', entry: { react: ['react', 'react-dom'] }, output: { filename: '_dll_ [name]. Js', / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- after the package is (_dll_react. Js) path: Path.resolve (__dirname, 'dist'), library: '_dll_[name]', // assign the value of the package to the _dll_[name] variable. 'var', // variable type}, plugins: [new webpack DllPlugin ({/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - webpack. DllPlugin used to generate the task list, namely the manifest. The json file name: '_dll_[name]', // name indicates the name of the library exposed globally // Note: Be consistent in the name and the output. Librry / / note: the name is representative of packaging generated after manifest in the dist directory. The json variable values in the path: Path.resolve (__dirname, 'dist', '[name].manifest. Json ')})]} NPX webpack --config webpack.config.react. Js (1) _dll_react. Js / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - the contents of the file will be assigned to a variable (_dll_react) (2) the manifest. Json file -- -- -- -- -- - (3) webpack. Config. Js plugins: [new webpack. DllReferencePlugin ({/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the manifest reference list: Path.resolve (__dirname, 'dist', 'react.manifest.json') //- reference the manifest.json file}), ----- (4) index.js import react from 'react' import {render} from 'react-dom' render(<h1>jsx</h1>, Document.getelementbyid ('root')) (5) Effect: Package main.js from (1.4m => 500KB)Copy the code

Happypack ————————- Multithreaded packaging

  • happypack
module.rules:
{
  test: /\.js$/,
  use: 'happypack/loader?id=js',
  },
}

plugins:
new HappyPack({
    id: 'js',
    use: [{
        loader: 'babel-loader'
    }]
})
Copy the code

Code segmentation optimization.splitchunks

Vendors => chunks => cacheGroups => Vendors and Commons-priority: -optimization: {minimizer: {}, // compress CSS and JS configuration items splitChunks: {cacheGroups: {Commons: {name: 'Commons' chunks:' initial 'minChunks: 1, the priority: 10, minSize: 0,}, vendors: {/ / vendor means vendor test: // node_modules/, // the scope is the third-party dependencies within node_modules. Note: Zhe name: 'vendors', // pull out the package name chunks: MinSize: 0,}}}}Copy the code

@ Babel/plugin – syntax – dynamic – import – — — — — — — — — — — — — — — — — — — — — to implement lazy loading

  • npm install @babel/plugin-syntax-dynamic-importDynamic syntax import
  • Syntax: grammar
  • Dynamic: dynamic
Module: {rules: [{test: /\.js$/, use: [{loader: 'babel-loader', options: { presets: { ['@babel/preset-env'], ['@babel/preset-react'], }, plugins: { ['@babel/plugin-proposal-decorators', {'legacy': true}], ['@babel/plugin-proposal-class-properties', {'loose': true], ['@babel/plugin-transform-runtime'], ['@babel/plugin-syntax-dynamic-import'] } } }, { loader: 'eslint-loader', options: { enforce: 'pre' } } ] } ] } (2) index.js const button = document.createElement('button') button.innerHTML = 'button' button.addEventListener('click', () => { console.log('button clicked') import('./dynamic.js').then(res => console.log(res.default, 'res')) / / -- -- -- -- -- -- -- -- -- -- - grammar dynamic import, implement}) using a json document. The body. The appendChild (button) and (3) - the import can only be used at the top an error: {"parser": "babel-eslint", "parserOptions": {"parser": "babel-eslint", "parserOptions": { "sourceType": "module", "allowImportExportEverywhere": True, / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- in all places can import and export}, "rules" : {" indent ":" off "}, "env" : {}} - https://stackoverflow.com/questions/39158552/ignore-eslint-error-import-and-export-may-only-appear-at-the-top-levelCopy the code

Webpack. HotModuleReplacementPlugin and webpack. NameModulesPlugin — — — — — — — — — hot update

- hot update - new webpack. HotModuleReplacementPlugin () / / hot update - new webpack NameModulesPlugin () / / print the path of the hot update module 1. Add hot: true to the devServer configuration to enable hot update-2. In the plugins in an array of new webpack. HotModuleReplacementPlugin () and new webpack NameModulesPlugin () - 3. (1) devServer: {contentBase: path.join(__dirName, 'dist'), port: '5000', compress: true, open: true, hot: True, / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- hot: true open hot update mode / / proxy: {/ / '/ API: {/ / target: 'http://localhost:7000', // pathRewrite: { // '^/api': '' // } // } // }, before(app) { app.get('/api/user', (req, res) => { res.json({ user: 'woow_wu7' }) }) } }, (2) plugins: [ new HtmlWebpackPlugin({ template: './src/index.html', filename: 'index.html', hash: true, minify: { removeAttributeQuotes: true, collapseWhitespace: true, } }), new MiniCssExtractPlugin({ filename: 'css/main.css' }), // new CleanWebpackPlugin(), new CopyWebpackPlugin([{ from: './src/copywebpackplugin', to: './' }]), new webpack.DefinePlugin({ DEV: JSON.stringify('DEV'), BOOLEAN1: true, BOOLEAN2: JSON.stringify(true) }), new webpack.IgnorePlugin({ resourceRegExp: /^\.\/local$/, contextRegExp: /moment$/, }), new webpack.ProvidePlugin({ $: 'jquery' }), new webpack.BannerPlugin({ banner: 'by woow_wu7' }), new webpack.NamedModulesPlugin(), / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - webpack. NameModulesPlugin print update module path. New webpack HotModuleReplacementPlugin () / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- Webpack. HotModuleReplacePlugin hot update plug-in / / new webpack DllReferencePlugin ({/ / manifest: path.resolve(__dirname, 'dist', 'manifest.json') // }) ], (3) index.js import hotNow from './hot'; The console. The log (hotNow) if (module. Hot) {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - if hot. The module, Open the hot update module. Hot. Accept ('. / hot. Js', function () {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- listening '. / hot. Js' change, if change, Execute callback const res = the require (". / hot. Js') / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- to reload, and print the latest value the console. The log (res, 'hot updated new return values')})}Copy the code

Write a Loader

  • Loader is a function, and the first argument represents the source code of the file that the loader matches.
  • I can’t write it as an arrow function because I need to get more API from this
  • this.query
    • How to get configuration parameters in loader :(options object)This. Query refers to the options object
    • If the loader does not have options and instead calls the query string, this. Opening character
      • Note: this. Query is deprecated. Use the getOptions in Loader-utils to get the options object
  • loader-utils
    • npm install loader-utils -D
    • Obtain the Options configuration object of the Loader from the getOptions in Loader-utils
  • this.callback
    • parameter
      • The first argument: err // Error or null
      • The second parameter: content // String or buffer, which is the processed source code
      • The third argument: sourceMap // is optional and must be a source map that can be resolved by the module
      • The fourth parameter: meta // is optional, that is, metadata
      • / / www.webpackjs.com/api/loaders…
  • this.async
    • Handles asynchronous operations in the Loader
    • The this.async() method returns this.callback
  • resolveLoader
    • Webpack configuration items
    • Configuration items of the resolveLoader
      • Modules: [‘node_modules’, ‘./ SRC /loaders’]
      • / SRC /loaders /loaders /loaders /loaders /loaders /loaders
  • loader API

The simplest replace-loader

Replace-loader -- directory: SRC/loaders/replace - loader. Js module. Exports = function (source) {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - loader is a function, Replace ('hello', 'hi! Webpack.config.js module: {rules: [{test: /\.js$/, use: [path.resolve(__dirname, './src/loaders/replace-loader.js')] }] }Copy the code

Updated version

Directory: webpack. Config. Js. (1) the module exports = {resolveLoader: {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- resolveLoader modules: ['node_modules', './ SRC /loaders/'] // loaders: 'the replace - loader', / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- loading replace loader, namely the filename options: {name: 'hi!!!!!!!! @!!!!!!!!!!!!!!! '/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the options property name}} directory: src/loaders/replace-loader const loaderUtils = require('loader-utils') // ---------------- loader-utils module.exports = Function (source) {console.log(this.query) // options Const options = loaderUtils.getoptions (this) // ------------- LoaderUtils. GetOptions (this) to obtain the options const callback = this. Async () / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - deal with asynchronous loader, This.callback setTimeout(function() {const result = source.replace('hello', options.name) callback(null, result) }, 1000) }Copy the code

data

I’m Jane books: www.jianshu.com/p/1fc4640f4… Webpack optimization: juejin.cn/post/684490… Process. The env www.jianshu.com/p/c8f9c61c2…