webpack4 or above version

1.mode attribute:

webpack needs to set the mode attribute to indicate whether it is a development environment or a production environment, which can be development or production, for example: webpack --mode development

Features provided by webpack for development mode: browser debugging tools, annotations, detailed error logs and prompts during the development phase, fast and optimized incremental build mechanism

Features provided by webpack for production mode: enable all optimized code, smaller bundle size, remove code that only runs in the development phase. Scope hoisting (put multiple bunnd.js in the same closure to speed up code execution ) and Tree-shaking (go into unused modules and remove it, reducing the size of the entire bunnd.js)

2. Plug-ins and optimization:

webpack4 removed the CommonsChunkPlugin plugin, which uses the built-in API optimization.splitChunks and optimization.runtimeChunk, which means that webpack will generate shared code chunks for you by default.

Other plugin changes:

NoEmitOnErrorsPlugin deprecated –> use optimization.noEmitOnErrors instead

ModuleConcatenationPlugin obsolete –> use optimization.concatenateModules instead

NamedModulesPlugin obsolete –> use optimization.namedModules instead

uglifyjs-webpack-plugin has been upgraded to v1.0

3. Out-of-the-box WebAssembly :

WebAssembly (wasm, assembly, allowing binary execution on the web, supplementing js performance.) will bring about a substantial improvement in runtime performance. Due to the popularity in the community, webpack4 supports it out of the box. You can directly import or export the local wasm module, or you can directly import C++, C or Rust by writing loaders.

4. Support a variety of module types, a total of five types:

javascript/auto: In webpack3, support for all module systems is enabled by default, including CommonJS, AMD, and ESM.

javascript/esm: only supports static modules like ESM

javascript/dynamic: only supports dynamic modules such as CommonJS and AMD

json: only supports JSON data, which can be used through require and import

webassembly/experimental: only supports wasm module, currently in the experimental stage

5.OCJS

The meaning of 0CJS is 0 configuration. Inspired by the Parcel packaging tool, webpack4 makes the cost of running the project as low as possible for developers. In order to achieve 0 configuration, webpack4 no longer requires webpack.config.js as the packaged entry configuration file. Its default entry is './src/' and the default exit is './dist', which is good for small projects Gospel.

6. New plug-in system

webpack4 has made many modifications to the plug-in system, providing new APIs for plug-ins and hooks. The changes are as follows:

All hooks are uniformly managed by the hooks object, which treats all hooks as extensible class attributes. ·

When adding a plugin, a plugin name must be provided.

When developing a plugin, you can choose sync/callback/promise as the plugin type.

The hook can be registered by this.hooks = { myHook: new SyncHook(…)}.

Note: When using webpack4, make sure to use Node.js version >= 8.9.4. Because webpack4 uses a lot of new JS syntax, they have been optimized in the new version of v8.

7. Install webpack

npm install webpack webpack-cli -g
// -g这里表示全局安装,也可以在自己项目中安装,将-g去掉,每个项目配置自己独有的打包模块,推荐全局安装,以节省自己内存空间,不过别人下载你的项目后需要知道webpack版本号,否则可能会报版本问题的bug

8. The basic use of webpack:

The most basic use of webpack is an input file and an output file. In a project, the input file is usually main.js, and the output file is the file packaged by webpack. This file name is usually configured in the webpack configuration file. Of course, it can also be passed webpack packs the output file, its command: webpack main.js -o bundle.js, where -o means output, followed by the file name, but usually these configurations are configured in the configuration file, so we only need a simple The command can complete the packaging, such as:

webpack.config.js basic configuration:

// 1.引入path包,webpack5中输出文件要求绝对路径,因此这需要引入path模块
const path = require('path')
module.exports = {
    
    
  // 2.打包入口文件
  entry: './src/main.js',
  // 3.打包输出文件
  output: {
    
    
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  // 4.开发环境下,建议打开该选项
  devtool: 'eval-source-map',
} 

package.json configures the packaging command (webpack4 and above are mandatory to specify the packaging environment, so –environment is required later):

// 生产环境 
"build": "webpack --mode=production"
// 开发环境
"dev": "webpack --mode=development"
// 热更新启动项目
"server": "webpack-dev-server"

Tips: Sometimes there are multiple entry files. At this time, multiple entry files can be configured, and the output files should be configured flexibly, such as:

module.exports = {
    
    
  // 入口文件可以配置多个,此时可以打包出多个打包文件
  entry: {
    
    
    main: './src/main.js',
    utils: './src/utils.js'
  },
  // 多个打包文件命名需要写成动态命名,name实际是入口配置中对象的key
  output: {
    
     
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].bundle.js'
  }
}

loaders:

Loaders are tools that process languages ​​such as TypeScript, Less, Sass, files, JSON, and Transpiling (converting various other languages ​​into js) into front-end recognizable tools. Loaders are a type of tool. When using a tool, you need to download it from npm first.

url-loader: When the size of the file is smaller than a certain value, convert the file to the base64 format, generally replacing the sprite image (the base64 format is recommended for small icons to reduce requests, because the base64 bit image is directly written in the file in the form of code )

babel-loader: Convert advanced syntax codes such as es6-es7 to es5, it needs to use components such as @babel/preset-env, @babel/plugin-proposal-object-rest-spread, and download it when using it, @babel /plugin-transform-react-jsx: React component processing: npm i @babel/plugin-transform-react-jsx -D , -D means that the development environment will only be used

Plugins:

A class of tools for packaging code processing. Here are a few commonly used plug-ins:

mini-css-extract-plugin: webpack puts the converted css code into the js file by default, which will cause the js file to be very bloated, so you can use mini-css-extract-plugin to extract the css code into a css code file , this module needs to be downloaded separately.

DefinePlugin: It is used to define, define some ip, etc., such as the definition of production environment ip and development environment ip, etc. This plug-in can be deconstructed from the webpack module.

html-webpack-plugin: a plugin used to generate html files, this plugin needs to be installed

devServer: hot replacement, after the code is modified, it will be automatically updated to the browser without refreshing the browser, this plug-in needs to be installed separately, npm i webpack-dev-server -g, pay attention to the package webpack-dev-server

webpack.config.js configuration file:

// 7-1: 引入mini-css-extract-plugin插件:
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
// 7-2: 解构定义配置插件:
const {
    
     DefinePlugin } = require('webpack')
// 7-3: 引入生成html文件的插件:
const htmlWebpackPlugin = require('html-webpack-plugin');
// 1.引入path包,webpack5中输出文件要求绝对路径,因此这需要引入path模块
const path = require('path')
module.exports = {
    
    
  // 2.打包入口文件
  entry: './src/main.js',
  // 3.打包输出文件
  output: {
    
     
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  // 4.开发环境下,建议打开该选项
  // devtool: 'eval-source-map',
  // 5.配置打包环境:production生产环境、development开发环境,一般在package.json文件中配置命令即可
  mode: 'production',
  // 6.配置loader:
  module: {
    
    
    rules: [
      // A.将图片文件处理为base64位文件:npm i url-loader -S ,将url-loader先安装到本地,-S表示同时需要记录在package.json中
      // 此时去打包提示需要安装file-loader,原因是图片属于文件类型,因此还需要file-loader,继续npm i file-loader -S安装,后面其它loader安装方式一样,我就不重复了
      {
    
    
        test: /\.(jpg|svg|png|gif)$/,
        use: [
          {
    
    
            loader: 'url-loader',
            options: {
    
    
              // 默认为true,即使用es6模块化;设为false,即使用commonJs模块语法
              esModule: false,
              outputPath: 'images',
              limit: 100*1024, // 小于100kb的图片转为base64
              name: '[hash].[ext][query]', // 自定义输出文件名
              // webpack5使用旧的assets loader(如file-loader/url-loader)
              // 可以加'javascript/auto'来解决图片无法生成images文件夹(目标文件夹)
              type: 'javascript/auto'
            }
          }
        ]
      },
      // B.处理js、react高级语法:
      {
    
    
        test: /\.(m?js|jsx)$/, // 处理js,和react文件
        exclude: /(node_modules|bower-components)/, // 忽略node_modules等文件
        use: {
    
    
          loader: 'babel-loader',
          options: {
    
    
            presets: ['@babel/preset-env','@babel/preset-react'], // @babel/preset-env核心对js高级语法解析的工具,@babel/preset-react解析react语法
            plugins: ['@babel/plugin-proposal-object-rest-spread'] // 处理react的工具
          }
        }
      },
      // C.处理sass:
      {
    
    
        test: /\.scss$/,
        use: [
          // 以下是未使用MiniCssExtractPlugin插件配置:
          // "style-loader",
          // "css-loader",
          // "sass-loader"

          // 使用MiniCssExtractPlugin插件配置:
          MiniCssExtractPlugin.loader,
          "css-loader",
          "sass-loader"
        ]
      }
    ]
  },
  // 7.插件:
  plugins: [
    // 7-1.从js文件抽离css代码到css文件:
    new MiniCssExtractPlugin({
    
    
      filename: 'css/[name].css',
      chunkFilename: '[id].css',
    }),
    // 7-2.定义配置,如不同环境的ip地址:DefinePlugin需要先从webpack中解构出来
    new DefinePlugin({
    
    
      // 这里定义的:SERVICE_URL可以在项目其他文件中使用
      'SERVICE_URL':JSON.stringify('https://blog.csdn.net/weixin_46758988')
    }),
    // 7-3:生成html文件:htmlWebpackPlugin默认可以什么也不配置,如果想要生成自定义html文件,那么就要对其配置:
    new htmlWebpackPlugin({
    
    
      title: 'my-app', // 用来设置网站标题
      filename: 'index.html', // 设置文件名,默认就为:index.html
      template: './src/index.html', // 默认html模板,在这个文件可以引入项目所依赖的其他文件
    })
  ],
  // 8.热替换:
  devServer: {
    
    
    // contentBase: path.join(__dirname,'dist'), // 启动文件位置,版本问题,开启会报bug
    compress: true, // 是否压缩代码
    port: 9000, // 端口
    // hot: false // 热替换,false表示热替换,true表示不热替换
  },
  // 9.webpack自身配置:
  // configureWebpack: {
    
    
  //   // 是否开启代码性能提示:有些文件大小超过webpack默认的配置大小会报警告
  //   performance: {
    
    
  //     hints: false, // 关闭,其值还可以是:warning表示警告:
  //     // 入口起点的最大体积
  //     maxEntrypointSize: 50000000,
  //     // 生成文件的最大体积
  //     maxAssetSize: 30000000,
  //     // 只给出 js 文件的性能提示
  //     assetFilter: function(assetFilename) {
    
    
  //       return assetFilename.endsWith('.js');
  //     }
  //   },
  // }
}

// module.exports = {
    
    
//   // 入口文件可以配置多个,此时可以打包出多个打包文件
//   entry: {
    
    
//     main: './src/main.js',
//     utils: './src/utils.js'
//   },
//   // 多个打包文件命名需要写成动态命名,name实际是入口配置中对象的key
//   output: { 
//     path: path.resolve(__dirname, 'dist'),
//     filename: '[name].bundle.js'
//   }
// }

Tips: The pictures and other materials in this article come from the Internet. If there is any infringement, please send an email to the mailbox: [email protected] to contact the author to delete it.
Author: sea of ​​bitterness

Guess you like

Origin blog.csdn.net/weixin_46758988/article/details/131270819