Webpack 5.0 configuration

1.webpack.common.js File Configures common configuration loader and plugin

Webpack 5.0 configuration has been simplified a lot, loader file rule configuration parameter location has been changed

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// Import plugins that delete folders each time
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

// Reuse loader
const commonCssLoader = [MiniCssExtractPlugin.loader];
module.exports = {
  // SRC /index.js is not required after WebPack 4.0
  entry: './src/acc-ivr-sdk.js'.// The export file defaults to./dist/main.js and is not required after WebPack 4.0
  output: {
    path: path.resolve(__dirname, '.. /dist'),
    filename: 'accIvrSdk.min.js'.libraryTarget: 'umd'.library: 'Menu',},module: {
    rules: [{test: /\.css$/,
        use: [...commonCssLoader, 'css-loader'],}, {test: /\.less$/,
        include: [
          path.resolve(__dirname, '.. /src/routes'),
          path.resolve(__dirname, '.. /src/components')],// commonCssLoader conflicts with style-loader and cannot be used at the same time
        use: [
          ...commonCssLoader,
          {
            loader: 'css-loader'.options: {
              sourceMap: true.modules: {
                // Keep the path babel-plugin-react-CSS-modules generateScopedName consistent
                localIdentName: '[path]___[name]__[local]___[hash:base64:5]',}}},'postcss-loader'.'less-loader',]}, {test: /\.less$/,
        include: [path.resolve(__dirname, '.. /src/styles')].use: [...commonCssLoader, 'css-loader! less-loader? modules'],}, {test: /\.scss$/,
        use: [
          ...commonCssLoader,
          'css-loader! sass-loader! @ali/next-theme-loader? theme=@alife/dpl-cdnext',]}, {/ / js | JSX code compatibility processing
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loader: 'babel-loader'.Core-js dependencies need to be installed after version 7.4.0
        options: {
          plugins: ['lodash'].// Lodash loads on demand
          presets: [['@babel/preset-env'.// Base presets
              {
                useBuiltIns: 'usage'.// Load as needed
                corejs: {
                  version: 3,},targets: {
                  // What version is compatible to the browser
                  chrome: '60'.firefox: '50'.ie: '9'.safari: '10'.edge: '17',},},],],},}, {test: /\.(png|gif|bmp|jpg|svg)$/,
        include: path.resolve(__dirname, '.. /src/styles/images/commons'),
        use: {
          loader: 'url-loader'.options: {
            limit: 8 * 1024.// The image takes a 10-bit hash and file extension
            name: '[hash:10].[ext]'.// Disable es6 modularization
            esModule: false,},},},],},plugins: [
    // The CSS code is extracted separately
    new MiniCssExtractPlugin({
      filename: 'main.min.css',}).// CSS code compression
    new OptimizeCssAssetsWebpackPlugin(),
    // HTML file compression
    new HtmlWebpackPlugin({
      template: './src/index.html'.minify: {
        // Remove whitespace
        collapseWhitespace: true.// Remove comments
        removeComments: true,}}),// Delete the dist file before each generation to keep it up to date
    new CleanWebpackPlugin(),
    // Lodash loads on demand
    new LodashModuleReplacementPlugin(),
    // Load the Monet locale on demand
    new MomentLocalesPlugin({
      localesToKeep: ['es-us'],}),],resolve: {
    extensions: ['.js'.'.jsx'.'.json'].alias: {
      // Take alias, relative path
      Components: path.resolve(__dirname, '.. /src/components'),
      Models: path.resolve(__dirname, '.. /src/models'),
      Routes: path.resolve(__dirname, '.. /src/routes'),
      Utils: path.resolve(__dirname, '.. /src/utils'),
      Styles: path.resolve(__dirname, '.. /src/styles'),
      Config: path.resolve(__dirname, '.. /config'),}}};Copy the code

2. Configure the local environment with webpack.dev.js

const webpackMerge = require('webpack-merge').merge;
const path = require('path');
const common = require('./webpack.common.js');

const devServerWebpack = webpackMerge(common, {
  /* The WebPack team introduced a configuration property called mode to implement zero-configuration (#oCJS) module packaging. Mode can be set to the following values: Development and production. Out of the box, the default is Production. The Production option provides a set of default configurations, which can be: smaller output size Quick loading code at runtime omit only development-time code not exposed source code or quick use of output Assets Development option provides the following default configurations, which can: Better tools for in-browser debugging in a fast development cycle, faster incremental compilation and better runtime error prompts */

  mode: 'development'.watch: true.watchOptions: {
    ignored: /node_modules/,},output: {
    path: path.resolve(__dirname, '.. /dist'),
    filename: 'accIvrSdk.js'.libraryTarget: 'umd'.library: 'Menu',},devServer: {
    contentBase: path.join(__dirname, '.. /dist'),
    compress: true.port: 9000.hot: true.open: true,}});module.exports = devServerWebpack;

Copy the code

3. Configure the online environment for webpack.prod.js

const webpackMerge = require('webpack-merge').merge;
const path = require('path');
const common = require('./webpack.common.js');

module.exports = webpackMerge(common, {
  mode: 'production'.output: {
    path: path.resolve(__dirname, '.. /dist'),
    filename: 'accIvrSdk.min.js'.libraryTarget: 'umd'.library: 'Menu',}});Copy the code

4. Babel. Config. Js bebel configuration

The configuration is in the root directory

/* the difference between.babelrc and babel.config.js. And Babel. Config. Js's role in global https://www.babeljs.cn/docs/configuration * /

const genericNames = require('generic-names'); / / v3.0.0
const CSS_MODULE_LOCAL_IDENT_NAME =
  '[path]___[name]__[local]___[hash:base64:5]';

module.exports = {
  presets: [
    '@babel/preset-env'.// Convert the latest syntax
    '@babel/preset-react',].plugins: [[/ / if you don't use the module USES less style need the className = {style.css. Container} after using the module can be simplified as written styleName https://zhuanlan.zhihu.com/p/34748443
      'babel-plugin-react-css-modules',
      {
        exclude: 'node_modules'.// The localIdentName of csS-modules must be the same as that of localIdentName
        // https://github.com/gajus/babel-plugin-react-css-modules/issues/291
        // generic-names is used to resolve the compatibility of CSS-Loader V4 HASH
        // Less Loader is configured with consistent path rules. GenericNames are not used to cause inconsistent CSS hashes generated by the main.min. CSS file and dom
        generateScopedName: genericNames(CSS_MODULE_LOCAL_IDENT_NAME),
        filetypes: {
          '.less': {
            syntax: 'postcss-less',},},},],'@babel/plugin-transform-runtime'.// Generators /async, babel-Runtime /core-js (ES6->includes....) It will not pollute the overall environment.
    [
      '@babel/plugin-proposal-decorators',
      {
        legacy: true,}], ['@babel/plugin-proposal-class-properties',
      {
        loose: true,}], ['@babel/plugin-proposal-private-methods', { loose: true}]],};Copy the code

5. Package. Json configuration

"scripts": {
    "build-sdk-def": "webpack server --config=./webpack/webpack.dev.js --progress"."build-sdk-min-def": "webpack --config=./webpack/webpack.prod.js --progress",},"devDependencies": {
    "@babel/core": "^ 7.14.6"."@babel/plugin-proposal-class-properties": "^ 7.14.5"."@babel/plugin-proposal-decorators": "^ 7.14.5"."@babel/plugin-transform-runtime": "^ 7.14.5"."@babel/preset-env": "^ 7.14.7"."@babel/preset-react": "^ 7.14.5"."autoprefixer": "^ 7.1.2." "."babel-loader": "^ 8.2.2"."babel-plugin-lodash": "^ 3.3.4." "."clean-webpack-plugin": "^ 4.0.0 - alpha."."core-js": "^ 3.15.2"."cross-env": "^ 7.0.3." "."css-loader": "^ 5.2.6." "."extract-text-webpack-plugin": "^ 2.1.0." "."generic-names": "^ 3.0.0"."html-webpack-plugin": "^ 5.3.2." "."less": "^ 4.4.1"."less-loader": "^ 10.0.0"."lodash-webpack-plugin": "^ 0.11.6"."mini-css-extract-plugin": "^ 1.6.2"."moment-locales-webpack-plugin": "^ 1.2.0"."optimize-css-assets-webpack-plugin": "^ the 6.0.1." "."postcss": "^ the 6.0.1." "."postcss-less": "^ 4.0.1." "."postcss-loader": "^ 6.1.0"."style-loader": "^ 3.0.0"."url-loader": "^ 4.1.0." "."webpack": "^ 5.41.1"."webpack-bundle-analyzer": "^ 4.4.2." "."webpack-cli": "^ 4.7.2." "."webpack-dev-server": "^ 3.11.2"."webpack-merge": "^ 5.8.0"
}
Copy the code