webpack4 configuration you have mastered it?

webpack5 is out, the basic configuration of the webpack4, analytical ES6, the introduction of CSS, compiler Less, image settings, etc., you will begin?

Analysis ES6

Learn Babel

Babel is a JavaScript compiler can be implemented into code ES6 + browser can be identified.

Babel at compile-time, you can rely .babelrc file that, when set dependent files, reads from the root directory of the project .babelrc configuration items, .babelrc profile mainly on the default (presets) and plug-ins (plugins) configuration.

Wherein, Presets source may be identified using the need to convert new features which can be understood as a series of set of plugins, e.g. babel-preset-es2015, may be converted to ES5 es6; plugins and indicates how the code conversion babel, e.g. plugin-transform-arrow-functions can be converted ES6 syntax is ES5.

Analysis ES6

1, mounted reliance

npm i @babel/core @babel/preset-env babel-loader -D

2, the configuration settings loader webpack.config.js

 module: {
        rules: [
            {
                test: /.js$/,
                use: 'babel-loader'
            }
        ]
    }

3, the root directory is created .babelrc, and configure preset-env for ES6 + syntax conversion characteristics

{
  "presets": [
    "@babel/preset-env"
  ]
}

Resolve React: JSX

1, mounted and react @ babel / preset-react

npm i react react-dom @babel/preset-react -D

2, the configuration parsing React presets

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ]
}

CSS parsing and Less

css-loader: .css file for loading and converted to commonjs object.
style-loader: the style is inserted into the head by style tags.

1, mounted reliance css-loader and style-loader

npm i style-loader css-loader -D

2, webpack added configuration item loader configuration, since the execution order in which the loader is performed from right to left, it will first perform label insertion parses style css style.

 

{
   test:/.css$/,
   use: [
      'style-loader',
      'css-loader'
   ]
}

3, less-loader, converted into less css. Less-loader is mounted upon and adding configure webpack

 

{
    test:/.less$/,
    use: [
         'style-loader',
         'css-loader',
         'less-loader'
    ]
}

Analytical pictures and fonts

file-loader

file-loader: work with files and fonts.

And configured in dependence file-loader

npm i file-loader -D
{
   test: /\.(png|svg|jpg|jpeg|gif)$/,
   use: 'file-loader'
},
{
    test:/\.(woff|woff2|eot|ttf|otf|svg)/,
    use:'file-loader'
}

 

url-loader

url-loader can handle files and fonts advantage, comparative file-loader is that by setting the configuration settings are automatically converted into a small resource base64.

Url-loader is mounted upon and disposed webpack.

{
     test: /\.(png|svg|jpg|jpeg|gif)$/,
      use: [
           {
               loader:'url-loader',
               options: {
                   limit:10240
               }
           }
      ]
}

File monitor: watch

By changing the listening source, automatically build a new output file.

You can add or CLI configuration by adding webpack way open listening mode, you need to manually refresh your browser each time change the way Source:

1, webpack configuration settings

 

module.export = {
    watch: true
}

2, CLI add parameters: - watch.

Except through the watch open listening configuration parameters can also be in the form of custom watch mode option watchOptions to customize the monitor configuration.

 

= module.export { 
    Watch: to true ,
     // only opened a listening mode, only the effective 
    watchOptions: { 
        ignored: / node_modules /, // empty by default, setting is not listening files or folders 
        aggregateTimeout: 300, // default 300ms , the execution time of change after listening to wait 
        poll: 1000    // default 1000ms, by way of polling asked to specify whether the file system changes 
    } 
}

Thermal Update: webpack-dev-server

The basic principle of hot update

Hot update about the process:

webpack Compiler, will be compiled into JavaScript bundle file output.
HMR Server, the heat output of the updated file to HMR Runtime.
Bundle Server, by providing the server in the form of providing browser access to files.
HMR Runtime, when packaging development stage, will build the output file is injected into the browser, the update file changes.

When starting webpack-dev-server stage, the source code in the file system to compile, package by webpack Compiler Compiler, compiled and submitted to the Bundle Server file server; that is the way Bundle Server can server for browser access.

When a change occurs to listen to the source, after compiling webpack Compiler submitted to the HMR Server, usually to achieve change through listening source websocket, and notify the HMR Runtime via json format data, HMR Runtime bundle to change and refresh your browser.

Hot update configuration

Compared to watch does not automatically refresh the browser, the advantages webpack-dev-server on the obvious. webpack-dev-server build content will be stored in memory, so to build faster, and can automatically recognize the browser automatically and make changes. Wherein, webpack-dev-server need to be used with the built-in HotModuleReplacementPlugin WebPACK plug.

1, mounted reliance webpack-dev-server configuration and startup items

npm i webpack-dev-server -D
// package.json
"scripts": {
    "dev": "webpack-dev-server --open"
}

 

2, the configuration WebPACK, wherein webpack-dev-server is generally used in a development environment, it is required to set the mode to mode development.

 

the require WebPACK = const ( 'WebPACK' ) 
plugins: [ 
     new new webpack.HotModuleReplacementPlugin () 
    ], 
    devserver: { 
        ContentBase: path.join (__ dirname, 'dist'), // listening dist folder contents 
        Hot: to true // Start hot update 
}

For more configuration items may refer to: https://www.webpackjs.com/configuration/dev-server/

File fingerprint

hash: Construction of the entire project related, when there are file modification, the entire project to build the hash value is updated.
chunkhash: webpack packaged and associated chunk, a different entry may generate different chunkhash, generally used for packaging of js.
contenthash: to define the hash based on the contents of the file, the file contents remain unchanged, contenthash unchanged. Css example of packaging, due to the modification or js html file, but without modifying the introduced css style, the file does not need to generate a new hash value, it is applicable to packaging css.

Notes, file fingerprint can not be used in conjunction with hot update.

JS file fingerprint settings: chunkhash

webpack.dev.js

 

module.export = {
     entry: {
           index: './src/index.js',
           search: './src/search.js'
        },
        output: {
            path: path.resolve(__dirname,'dist'),
            filename: '[name][chunkhash:8].js'
        },
}

CSS file fingerprint: contenthash

Since the above manner by the CSS style tag is inserted into the head and does not generate separate CSS file, we can min-css-extract-plugin plugin extracted into separate CSS CSS file and add a file fingerprint.

1, the installation-dependent mini-css-extract-plugin

npm i mini-css-extract-plugin -D

2, the configuration file fingerprint CSS

const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.export = {
    module: {
        rules: [
            {
                test:/\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                ]
            },
        ]
    },
     plugins: [
        new MiniCssExtractPlugin({
           filename: '[name][contenthash:8].css'
        })
     ]
}

Picture file fingerprint settings: hash

Wherein, the hash is a hash value corresponding to contents of the file, the default is md5 generated hash value is different from the aforesaid.

module.export = {
    module:{
        rules: [
            {
                 test: /\.(png|svg|jpg|jpeg|gif)$/,
                 use: [{
                     loader:'file-loader',
                     options: {
                         name: 'img/[name][hash:8].[ext]'
                     }
                 }],           
            }
        ]
    }
}

Code compression

Which js compression, webpack4.x version has built uglifyjs-webpack-plugin achieve compression.

CSS file compression: optimize-css-assets-webpack-plugin

1, mounted optimize-css-assets-webpack-plugin and preprocessor cssnano

npm i optimize-css-assets-webpack-plugin cssnano -D

2, the configuration webpack

const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin')
module.export = {
    plugins: [
         new OptimizeCssAssetsPlugin({
             assetNameRegExp: /\.css$/g,
             cssProcessor: require('cssnano')
         })
    ]
}

html file compression: html-webpack-plugin

1, the mounting plug html-webpack-plugin

npm i html-webpack-plugin -D

2, the configuration webpack

the require HtmlWebpackPlugin = const ( 'HTML-WebPACK-plugin' ) 
module.export = { 
    plugins: [ 
         new new HtmlWebpackPlugin ({ 
             Template: path.join (__ dirname, 'the src / the search.html'), // use the template 
             filename: 'search .html ',     //   file name of the package 
             of chunks are: [' Search '], // chunk after packaged need to use (file) 
             the inject: to true , // default inject all static resources 
             Minify: { 
                  html5: to true , 
                  collapsableWhitespace: to true  ,
                  preserveLineBreaks:false,
                  minifyCSS: true,
                  minifyJS: true,
                  removeComments: false
             }
         }),
    ]
}

Corresponding complete demo code to view the address: https://github.com/PCAaron/blogCode/tree/master/webpack/webpack-basic

recommend

Subsequent articles priority update on GitHub and public numbers, we welcome the star and focus for the latest articles in advance, thanks ~

GitHub:https://github.com/PCAaron/PCAaron.github.io

No public: front-end cuisine sinks, can also directly scan the text at the end of direct concern to the two-dimensional code

webpack learning process

webpack Profile

  • Construction of the history of

Basics: the basic usage webpack

  • The basic usage webpack
  • Advanced use of webpack

Advanced article: webpack building optimization

  • Writing maintainable webpack build configuration
  • Construction velocity and volume optimization webpack

Principle chapter: pack of principle webpack

 

Recommended Reading

Babel:https://babeljs.io/docs/en/

webpack-dev-middleware:https://github.com/webpack/webpack-dev-middleware

webpack hot update Principle: https://segmentfault.com/a/1190000020310371

 

Guess you like

Origin www.cnblogs.com/aaron-pan/p/12164995.html
Recommended