1. Set up the basic WebPack environment

1.1 webpack

Webpack is a static module packaging tool for modern JavaScript applications. It analyzes the modules that your project depends on and extension languages (Scss, TypeScript, etc.) that browsers don’t run directly, and generates one or more bundles. Package it into an appropriate format for your browser to use.

1.2 Initializing the Project

npm init -y

1.3 installation webpack

  • Install the node
Check whether the installation is successful. Node -v NPM -vCopy the code
  • Install the NRM
// When using the official NPM source to install various packages is slow, it is recommended to download NRM (NPM source manager) to quickly switch between different NPM source addresses. NPM install NRM - g / / check the optional source NRM ls / / suggest to switch to the taobao mirror NPM install - g CNPM - registry=https://registry.npm.taobao.org NRM use NRM add <registry> <url> // delete del <registry>Copy the code
  • Install webpack
Webpack-cli is a command line for webpack, webpack4.0 or later, separate webpack from webpack-CLI. Run the webpack-related command CNPM install webpack webpack-cli -g webpack -v // install webpack locally and check whether the installation is successful webpack-cli -D npx webpack -vCopy the code

1.3 WebPack packages build projects

  • project
webpack-demo |- package.json |- package-lock.json |- webpack.config.js |- postcss.config.js + |- /src + |- css + |- js +  |- images + |- index.js + |- index.html + |- /dist + |- bundle.js + |- index.html + |- imagesCopy the code
  • NPM specifies entry and exit file paths (not recommended)
/dist/main.js NPX webpack. / SRC /index.js --mode development // specify import file and export file path NPX webpack by default ./src/index.js -o ./dist/bundle.js --mode developmentCopy the code
  • Create the webpack.config.js file under the project file and specify the path to the entry and exit files
    var path = require('path')
    module.exports = {
      mode: 'production'// Two modes, development mode and production mode (will compress the export file) entry:'./src/index.js'// output: {path: path.resolve(__dirname,'./dist'), // export file //path: path.jion(_dirname,'./dist')
        filename: 'bundle.js'}}Copy the code

Run NPX Webpack in NPM for a packaged build

2. Basic Configuration of webPack

2.1 loaders

Webpack default only with packaging type JS file, if you want to handle the JS file type, such as suffix for. CSS /. Less /. SCSS /. PNG /. Vue files, such as need to manually install third-party file loader loader to pretreatment

2.1.1 Loading the CSS File

  • The installation
npm i style-loader css-loader -D
Copy the code
  • In the webpack.config.js file
module: {
    rules: [
      { 
        test: /\.css$/, 
        use: ['style-loader'.'css-loader'] // Load rules from top to bottom, right to left // cS-loader will combine multiple CSS files into a CSS, style loader will mount this CSS on the header element of the HTML page}]}Copy the code

2.1.2 Loading the LESS File

  • The installation
npm  i less less-loader -D
Copy the code
  • In the webpack.config.js file
module: {
    rules: [
      {
        test: /\.less$/,
        use: ['style-loader'.'css-loader'.'less-loader']]}}Copy the code

2.1.3 Loading the SCSS File

  • The installation
NPM I Sas-loader -d // It is recommended that NRM switch to Taobao image and use CNPM to download Sas-loader instead of NPM after switching, the basic download fails (of course, it depends on PC) // If NPM downloads dependent packages after switching, errors are often reported later. Need to download again, may use NPM and CNPM command conflict. // The node_modules file needs to be deleted and CNPM I sas-loader -d needs to be re-installed on NPMCopy the code
  • In the webpack.config.js file
module: {
    rules: [
      {
        test: /\.less$/,
        use: ['style-loader'.'css-loader'.'sass-loader']]}}Copy the code

2.1.4 Automatically Adding the CSS3 Prefix

  • The installation
npm i postcss-loader -D
npm i autoprefixer -D
Copy the code
  • Create the postcss.config.js file in the project root directory
module.exports = {
  plugins: [
    require('autoprefixer')]}Copy the code
  • In the webpack.config.js file
module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          'style-loader', 
          {
            loader: 'css-loader', options: {importLoaders: 2, // If another sass file is imported from the sass file, the other file will be parsed up from the last loader. If not, start parsing directly from CSS-loader. // 0 => no loaders (default); 1 => postcss-loader; 2 => postcss-loader, sass-loader modules:true// Enable the CSS module packaging function. CSS styles do not couple or conflict with other modules}},'postcss-loader', / / configuration after the CSS - loader, in sass | less | style - loader before'sass-loader']},]}Copy the code

2.1.5 Loading Image, Font, and media Files

  • The installation
// Url-loader is similar to file-loader except that the file size is limited. If the file is smaller than the size limit, base64 encoding is returned. npm i url-loader -DCopy the code
  • In the webpack.config.js file
module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              name: '[name]_[hash:8].[ext]'.limit: 32000}}]}, {test: /\.(ttf|eot|svg|woff|woff2)$/,
        use: ['url-loader'] {},test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              name: '[name]_[hash:8].[ext]'.limit: 32000}}]}]}Copy the code

2.2 the plugins

There are some things that webPack can do for you when it runs to a certain point

2.2.1 HTML-webpack-plugin: After packaging, an HTML file is automatically generated in dist directory, and js generated by packaging is automatically introduced into this HTML file

  • The installation
npm i html-webpack-plugin -D
Copy the code
  • In webpack. Config. Js
var path = require('path')
var htmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    // path: path.jion(_dirname, './dist'),
    filename: 'bundle.js'}, plugins: new htmlWebpackPlugin({template: path.resolve(__dirname,'./dist/index.html'),
      filename: 'index.html'}})]Copy the code

2.2.2 clean-webpack-plugin: Automatically clean the last packaged dist file

  • The installation
npm i clean-webpack-plugin -D
Copy the code
  • In webpack. Config. Js
var path = require('path')
var htmlWebpackPlugin = require('html-webpack-plugin')
var cleanWebpackPlugin = require('clean-webpack-plugin')
module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    // path: path.jion(_dirname, './dist'),
    filename: 'bundle.js'}, plugins: new htmlWebpackPlugin({template: path.resolve(__dirname,'./dist/index.html'),
      filename: 'index.html'
    }),
    new cleanWebpackPlugin()
  ]
}
Copy the code

2.3 Configuration for Packaging Multiple entry Files

In the webpack.config.js file

var path = require('path')
var htmlWebpackPlugin = require('html-webpack-plugin')
var cleanWebpackPlugin = require('clean-webpack-plugin')
module.exports = {
  mode: 'development',
  entry: {
    main: './src/index.js',
    bundle: './src/index.js'
  },
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: '[name].js',           //main => main.js  bundle => bundle.js
    publicPath: 'http://cdn.com.cn'New htmlWebpackPlugin({template: path.resolve(__dirname,}); // Plugins: new htmlWebpackPlugin({template: path.resolve(__dirname,});'./dist/index.html'),
      filename: 'index.html'
    }),
    new cleanWebpackPlugin()
  ]
}
Copy the code

2.4 SourceMap: Package the mapping between compiled files and source files for developer debugging

In the webpack.config.js file

module.exports = {
    mode: 'development',
    devtool: 'cheap-module-eval-source-map',
    //devtool:'none'// In developer mode, sourcemap is enabled by default, and devtool is disabled.'source-map'// Devtool:'inline-source-map'// Instead of generating a separate.map file, the generated map file is inserted into the bottom of the packaged JS file as base64.'cheap-inline-source-map'//devtool: < span style = "max-width: 100%; clear: both; min-height: 1em;'cheap-module-inline-source-map'// Devtool:'eval'// Devtool: < span style = "max-width: 100%; clear: both;'cheap-module-eval-source-map'// DevTool:'cheap-module-source-map',// In the production environment recommended to use the prompt effect is better}Copy the code

2.3 Webapck-dev-server: Realize automatic packaging and compilation function (hosting dist file in memory) and enable hot update function

  • The installation
npm i webpack-dev-server -D
Copy the code
  • Methods a
Json file // Webpack-dev-server is installed locally and cannot be used as a script command. Running on a Powershell terminal (only a global -G installation is available) requires some commands to be configured in the scripts of package.json to run"scripts": {
    "dev": "webpack-dev-server --open --port 3000 --contentBase dist --hot"}, //3. Run 'NPM run dev' in NPM to do automatic package compilationCopy the code
  • Method 2
//1. In package.json file"scripts": {
    "dev": "webpack-dev-server"}, //2. Var webpack = require('webpack'). The module exports = {plugins: [/ / configure the plug-in node new webpack HotModuleReplacementPlugin () / / open hot update], devServer: {open:true, // automatically open browser port: 3000, // development server listening port contentBase:'./dist'// configure the root directory of the development service runtime hot:true// Enable hot update hotOnly:true}} //3. Run 'NPM run dev' in NPM to do automatic package compilationCopy the code
  • Methods three
Var webpack = require();'webpack'). The module exports = {plugins: [/ / configure the plug-in node new webpack HotModuleReplacementPlugin () / / open hot update], devServer: {open:true, // automatically open browser port: 3000, // development server listening port contentBase:'./dist'// configure the root directory of the development service runtime hot:true// Enable hot update hotOnly:true}} //3. Run 'NPX webpack-dev-server' on NPM for automatic package compilation // from version 5.2, NPM has added the NPX command to use the tools installed locally, without the need to configure scripts in package.jsonCopy the code
  • In the index. In js
// If the module has HMR enabled, you can use module.hot.accept() to listen for module updates.if (module.hot) {
  module.hot.accept('./library.js'.function() {// Perform some operations with the updated Library module... })}Copy the code

2.4 Babel: Transfer ES6/7/8 to ES5 code

2.4.1 Mainly deals with business codes

  • The installation
NPM I babel-loader@babel /core -d NPM i@babel /preset-env -D ES6/7/8 syntax convert to ES5 syntax, However, the new API will not be converted and can be converted via core-js@3 NPM install core-js@3Copy the code
  • In the webpack.config.js file
module: {
  rules: [
    {
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'babel-loader',
      options: {
        presets: [
          [
            "@babel/preset-env", 
            {
            useBuiltIns: "usage"Corejs: 3,}]]}}]}Copy the code
  • Index. Js file
import "core-js/stable"
import "regenerator-runtime/runtime"
Copy the code

2.4.2 Developing class libraries, third-party modules or component libraries, using transform-Runtime can avoid declared variables becoming global variables, which will pollute the global environment

  • The installation
cnpm i @babel/plugin-transform-runtime @babel/runtime -D
cnpm i @babel/runtime-corejs3 -D
Copy the code
  • In the webpack.config.js file
{
  test: /\.js$/,
  exclude: /node_modules/,
  loader: 'babel-loader',
  options: {
    "plugins": [["@babel/plugin-transform-runtime",
        {
          "corejs": 3."helpers": true."regenerator": true."useESModules": false}]}}Copy the code

Source link: github.com/zhanglichun…