1. What is Webpack

According to the documentation, Webpack is essentially a static Module bundler for modern JavaScript applications. When WebPack works with an application, it recursively builds a Dependency graph containing every module the application needs, and then packages all of those modules into one or more bundles.

2. Four core concepts of Webpack

  • Entry entry, the first step in the build that WebPack performs will start with entry, which can be abstracted into input
  • Outputs the result after Webpack has gone through a series of processes to arrive at the final desired code
  • Loader module converter, used to convert the original content of a module into new content as required.
  • Plugins are extensions that broadcast corresponding events at specific times in the Webpack construction process. Plugins can listen for the occurrence of these events and do corresponding things at specific times.

2.1 entry

  • Three methods defined
Module. exports = {entry:'index.js'Module. exports = {entry:['index.js'.'b.js'Module. exports = {entry:{index: 0}'index.js',
          b:'b.js'}}Copy the code

The third method is recommended to distinguish the definitions of each entry

2.2 the output

  • Packaged files
  • One or more
module.exports = {
 entry:{
 index:'index.js',
 b:'b.js'
 },
 output:{
     path:path.resolve(__dirname,'dist'),
     filename:'[name].min.[hash:5].js'}}Copy the code

In the example above,

  • The name in output corresponds to the key in entry
  • Filename of output can specify a hash. There are two values to choose from:
    • [hash] : Hash values are specific to the entire build process.
    • [chunkhash] : The hash value is specific to the content of each file. Our ideal cache design is that after a version update (rebuild), a file needs to be re-downloaded only if its contents have actually changed, otherwise it should be cached. Therefore, the preferred value of the two above is [chunkhash]. You can also read this official caching guide for more details.

2.3 loader

  • What it does: By using different loaders, Webpack can convert different files into JS files, such as CSS, ES6/7, JSX, etc
  • parameter
    • Test: a regular expression that matches the extension of the processing file
    • Use: Loader name, which is the name of the module you want to use
    • Include /exclude: Manually specify the required folder or exclude the folder that does not need to be processed
    • Query: Provides additional Settings for loaders. The following uses CSS-loader as an example
    module: {
+        rules:[
+            {
+                test:/\.css$/,
+                use:['style-loader'.'css-loader'],
+                include:path.join(__dirname,'./src'),
+                exclude:/node_modules/
+            }
+        ]
   },  
Copy the code
  • The commonly used loader
    • Compile related babel-loader ts-loader
    • Style related style-loader CSS-loader less-loader postCSs-loader
    • File related file-loader url-loader

2.4 the plugins

  • Participate in the entire packaging process
  • Package optimization and compression
  • Configure compile-time variables
  • Usage (using compressed JS plug-ins as an example)
module.exports = {
    plugins: [
        new UglifyjsWebpackPlugin()
        ]
    }
Copy the code
  • Commonly used the plugin
    • Optimization of the related
      • CommonsChunkPlugin
      • UglifyjsWebpackPlugin
    • function
      • ExtractTextWebpackPlugin
      • HtmlWebpackPlugin
      • HotModuleReplacementPlugin
      • CopyWebpackPlugin

3. Common configuration of WBPack

3.1 Configuring the Development Server

npm i webpack-dev-server -D
Copy the code
    
       + devServer:{
+        contentBase:path.resolve(__dirname,'dist'),
+        host:'localhost',
+        compress:true,
+        port:8080
+ }
Copy the code
  • ContentBase configures the file root directory for the development service runtime
  • Host: indicates the host address monitored by the development server
  • Compress Indicates whether compression such as Gzip is enabled on the development server
  • Port: the port listened by the development server

3.2 Automatic OUTPUT of HTML

npm i html-webpack-plugin -D
Copy the code
   plugins: [
+        new HtmlWebpackPlugin({
+       minify: {
+            removeAttributeQuotes:true+ +}hash: true,
+        template: './src/index.html',
+        filename:'index.html'
    })]
Copy the code
  • Minify compresses HTML files. RemoveAttrubuteQuotes remove double quotes from attributes
  • Hash is added to output resources to avoid caching
  • Template template path

3.3 separation of CSS

Because CSS downloads and JS can be done in parallel, we can isolate CSS when an HTML file is large

    npm install --save-dev extract-text-webpack-plugin
Copy the code
   module: {
+        rules:[
+            {
+               test:/\.css$/,
+                use: ExtractTextWebpackPlugin.extract({
+                    use:'css-loader'
+                }),
                include:path.join(__dirname,'./src'),
                exclude:/node_modules/
+            }
+        ]
    },
     plugins: [
+        new ExtractTextWebpackPlugin('css/index.css')]
    
Copy the code

3.4 Compiling less and SASS

npm i less less-loader -D
npm i node-saas sass-loader -D
Copy the code
const cssExtract=new ExtractTextWebpackPlugin('css.css');
const lessExtract=new ExtractTextWebpackPlugin('less.css');
const sassExtract=new ExtractTextWebpackPlugin('sass.css');

 {
                test:/\.less$/,
                use: lessExtract.extract({
                    use:['css-loader'.'less-loader']
                }),
                include:path.join(__dirname,'./src'),
                exclude:/node_modules/
            },
            {
                test:/\.scss$/,
                use: sassExtract.extract({
                    use:['css-loader'.'sass-loader']
                }),
                include:path.join(__dirname,'./src'),
                exclude:/node_modules/
            },
Copy the code

3.5 Handling CSS3 Attribute Prefixes

For browser compatibility, we sometimes have to add prefixes like -webkit,-ms,-o, and -moz

  • Trident kernel: mainly represents Internet Explorer and is prefixed with -ms

  • Gecko kernel: Mainly represents Firefox and is prefixed with -moz

  • Presto kernel: Mainly represents Opera and is prefixed with -o

  • Webkit kernel: Represents Chrome and Safari with the prefix – Webkit

      npm i postcss-loader autoprefixer -D 
    Copy the code
module.exports={
    plugins:[require('autoprefixer')]} {test:/\.css$/,
                use: cssExtract.extract({
+                   use:['css-loader'.'postcss-loader']
                }),
                include:path.join(__dirname,'./src'),
                exclude:/node_modules/
            },
Copy the code

For other uses of postCSs-loader, refer to the documentation

3.6 escape ES6 / ES7

Babel is actually a platform for compiling JavaScript. It can escape ES6/ES7,React JSX to ES5

    npm i babel-core babel-loader babel-preset-env babel-preset-stage-0 babel-preset-react -D
Copy the code
{
        test:/\.jsx? $/, use: { loader:'babel-loader',
            options: {
                presets: ["env"."stage-0"."react"]
            }
        },
        include:path.join(__dirname,'./src'),
        exclude:/node_modules/
        },
Copy the code

3.7 Debugging the packaged code

Webapck is configured to automatically give us the sourcemaps file, and the map file is a method corresponding to the compiled file and the source file

  • Source-map generates the mapping file into a separate file, the most complete and the slowest
  • Cheap -module-source-map produces a map without a column map in a separate file
  • Eval-source-map uses eval to package the source file module, generating the full Sourcemap in the same file
  • Cheap -module-eval-source-map sourcemap and packaged JS are displayed together, with no mapped columns
module.exports = {
    devtool:'eval-source-map'
}

Copy the code

3.8 watch

Automatically recompile when code changes

new webpack.BannerPlugin(' '),

 watch: true, watchOptions: {ignored: /node_modules/, // Ignore aggregateTimeout: 500, // prevent repeated save frequent recompilation, repeated save within 500 mm without packing poll:1000 // Number of file changes queried per second},Copy the code

3.9 Copying Static Files

Sometimes files that are not referenced in the project need to be packaged into the target directory

npm i copy-webpack-plugin -D
Copy the code
 new CopyWebpackPlugin([{
            from: path.join(__dirname,'public'),// Static resource directory source address to:'./public'// Target address, relative to path of output}]),Copy the code

3.10 Clear packing first

npm i  clean-webpack-plugin -D
Copy the code
new cleanWebpaclPlugin(path.join(__dirname,'dist'))
Copy the code

3.11 Compressing JS/CSS

  • NPM I uglifyjs-webpack-plugin -d plugins: [new UglifyjsWebpackPlugin(),

  • Webpack eliminates unused CSS, such as the unused styles found in Bootstrap

    npm i -D purifycss-webpack purify-css
    npm i bootstrap -S
    Copy the code
{
                test:/\.css$/,
                use: cssExtract.extract({
                    use: [{
                         loader: 'css-loader',
 +                       options:{minimize:true}},'postcss-loader']})},Copy the code
Paths :glob. Sync (path.join(__dirname,))'src/*.html')) +}),Copy the code

4, summarize

The above is a summary of the core concepts of Webpack. The understanding of the concepts is helpful to have a general understanding of the different functions of Webpack and find the corresponding modules when you encounter relevant problems.Copy the code