2021-03-23

webpack production environment

The webpack development environment is more suitable for local debugging, and the production environment can be run online

Extract CSS into a separate file.
Benefits: Use link tags to import instead of style tags, which will not cause screen flickering.
Plug-ins need to be introduced. Here are the download instructions

npm i mini-css-extract-plugin -D

const {
    
     resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
    
    
  entry: './src/js/index.js',
  output: {
    
    
    filename: 'js/built.js',
    path: resolve(__dirname, 'build')
  },
  module: {
    
    
    rules: [
      {
    
    
        test: /\.css$/,
        use: [
          // 创建style标签,将样式放入
          // 'style-loader', 
          // 这个loader取代style-loader。作用:提取js中的css成单独文件
          MiniCssExtractPlugin.loader,
          // 将css文件整合到js文件中
          'css-loader'
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
    
    
      template: './src/index.html'
    })
    ,
    new MiniCssExtractPlugin({
    
    
      // 对输出的css文件进行重命名
      filename: 'css/built.css'
    })
  ],
  mode: 'development'
};

css compatibility processing
helps to identify certain environments, and load certain configurations, so that the compatibility can be accurate to the version of each browser, the following is the download instruction

npm i postcss-loader postcss-preset-env -D
is configured as follows in package.json

"browserslist": {
    
    
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ],
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ]
  }

The basic configuration is as follows

const {
    
     resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

// 设置nodejs环境变量
process.env.NODE_ENV = 'development';

module.exports = {
    
    
  entry: './src/js/index.js',
  output: {
    
    
    filename: 'js/built.js',
    path: resolve(__dirname, 'build')
  },
  module: {
    
    
    rules: [
      {
    
    
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          /*
            css兼容性处理:postcss --> postcss-loader postcss-preset-env

            帮postcss找到package.json中browserslist里面的配置,通过配置加载指定的css兼容性样式

            "browserslist": {
              // 开发环境 --> 设置node环境变量:process.env.NODE_ENV = development
              "development": [
                "last 1 chrome version",
                "last 1 firefox version",
                "last 1 safari version"
              ],
              // 生产环境:默认是看生产环境
              "production": [
                ">0.2%",
                "not dead",
                "not op_mini all"
              ]
            }
          */
          // 使用loader的默认配置
          // 'postcss-loader',
          // 修改loader的配置
        
          {
    
    
            loader: 'postcss-loader',
            options: {
    
    
              ident: 'postcss',
              plugins: () => [
                // postcss的插件
                require('postcss-preset-env')()
              ]
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
    
    
      template: './src/index.html'
    }),
    new MiniCssExtractPlugin({
    
    
      filename: 'css/built.css'
    })
  ],
  mode: 'development'
};

Pit
If the following error occurs, it is a problem of version mismatch

ValidationError: Invalid options object. PostCSS Loader has been
initialized using an options object that does not match the API
schema.

  • options has an unknown property ‘plugins’. These properties are valid: object { postcssOptions?, execute?, sourceMap?,
    implementation? }

Now what i am using is

To download the 3.0.0 version of postcss-loader again:

npm i [email protected] -D


Compared with loader, compressed css may be used more by plug-ins

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

const {
    
     resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')

// 设置nodejs环境变量
// process.env.NODE_ENV = 'development';

module.exports = {
    
    
  entry: './src/js/index.js',
  output: {
    
    
    filename: 'js/built.js',
    path: resolve(__dirname, 'build')
  },
  module: {
    
    
    rules: [
      {
    
    
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          {
    
    
            loader: 'postcss-loader',
            options: {
    
    
              ident: 'postcss',
              plugins: () => [
                // postcss的插件
                require('postcss-preset-env')()
              ]
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
    
    
      template: './src/index.html'
    }),
    new MiniCssExtractPlugin({
    
    
      filename: 'css/built.css'
    }),
    // 压缩css
    new OptimizeCssAssetsWebpackPlugin()
  ],
  mode: 'development'
};

js syntax check eslint

Configuration in package.json

“eslintConfig”: {
“extends”:“airbnb-base” }

If you don’t want to check the next line, you can use

// 下一行eslint所有规则都失效(下一行不进行eslint检查)
// eslint-disable-next-line(直接卸载js里面,注释了也会执行的)

Related configuration

const {
    
     resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');



module.exports = {
    
    
  entry: './src/js/index.js',
  output: {
    
    
    filename: 'js/built.js',
    path: resolve(__dirname, 'build')
  },
  module: {
    
    
    rules: [
      /*
        语法检查: eslint-loader  eslint
          注意:只检查自己写的源代码,第三方的库是不用检查的
          设置检查规则:
            package.json中eslintConfig中设置~
              "eslintConfig": {
                "extends": "airbnb-base"
              }
            airbnb --> eslint-config-airbnb-base(包含ES6的东西) eslint-plugin-import eslint
      */
      // {
    
    
      //   test: /\.js$/,
      //   exclude: /node_modules/,
      //   loader: 'eslint-loader',
      //   options: {
    
    
      //     // 自动修复eslint的错误
      //     fix: true
      //   }
      // }
                {
    
    
                  test:/\.js$/,
                  exclude:/node_modules/,
                  loader:'eslint-loader',
                  options:{
    
    
                    fix:true
                  }
                }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
    
    
      template: './src/index.html'
    })
  ],
  mode: 'development'
};

js compatibility handling

For example: If you use arrow functions, you may not have done compatibility processing. In some browsers, ES6 syntax
js compatibility processing may not be recognized : babel-loader @babel/preset-env @babel/core

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

(The following configurations are downloaded on demand)
js compatibility processing: babel-loader @babel/core
1. Basic js compatibility processing --> @babel/preset-env
problem: only basic syntax can be converted, such as promise advanced syntax cannot be converted
2. All js compatibility processing --> @babel/polyfill (reference directly in js, no configuration required)

import ‘@babel/polyfill’;

Question: I only need to solve some of the compatibility issues, but all the compatibility codes are introduced, which is too big~
3. Just do what needs to be compatible: load on demand --> core-js
4. @babel/preset -env and core-js can do all the compatibility processing

// const { resolve } = require('path');
// const HtmlWebpackPlugin = require('html-webpack-plugin');
const {
    
    resolve} = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');


module.exports = {
    
    
  entry: './src/js/index.js',
  output: {
    
    
    filename: 'js/built.js',
    path: resolve(__dirname, 'build')
  },
  module: {
    
    
    rules: [
      /*
        js兼容性处理:babel-loader @babel/core 
          1. 基本js兼容性处理 --> @babel/preset-env
            问题:只能转换基本语法,如promise高级语法不能转换
          2. 全部js兼容性处理 --> @babel/polyfill  
            问题:我只要解决部分兼容性问题,但是将所有兼容性代码全部引入,体积太大了~
          3. 需要做兼容性处理的就做:按需加载  --> core-js
      */  
      {
    
    
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
    
    
          // 预设:指示babel做怎么样的兼容性处理
          presets: [
            [
              '@babel/preset-env',
              {
    
    
                // 按需加载
                useBuiltIns: 'usage',
                // 指定core-js版本
                corejs: {
    
    
                  version: 3
                },
                // 指定兼容性做到哪个版本浏览器
                targets: {
    
    
                  chrome: '60',
                  firefox: '60',
                  ie: '9',
                  safari: '10',
                  edge: '17'
                }
              }
            ]
          ]
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
    
    
      template: './src/index.html'
    })
  ],
  mode: 'development'
};

Compress js and CSS compression
1. The js code will be compressed automatically in the
production environment. Many plugins will be downloaded in the production environment. One of the plugins, UglifyPlugin, will automatically compress the code.

const {
    
     resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    
    
  entry: './src/js/index.js',
  output: {
    
    
    filename: 'js/built.js',
    path: resolve(__dirname, 'build')
  },
  plugins: [
    new HtmlWebpackPlugin({
    
    
      template: './src/index.html'
    })
  ],
  // 生产环境下会自动压缩js代码
  mode: 'production'
};

2. Use the following statement to achieve
// compress html code
minify: { // remove whitespace collapseWhitespace: true, // remove comment removeComments: true }




Guess you like

Origin blog.csdn.net/qq_44073682/article/details/115108841