Webpack 打包配置实践

123 阅读3分钟

前言

我们使用vue等前端框架项目时一般都有像vue-cli 这样的脚手架,通常情况下我们要配置的文件是vue.config.js ,但是如果没有使用vue-cli的时候就需要配置自己的webpack.config.js 文件了。

一、webpack 的五个核心模块

  1. entry :入口,从那个文件开始打包
  2. output: 出口,输出到那里去 (bundle 的资源)
  3. loader: 处理非js或json 文件资源,(webpack 本身只处理js和json 文件,需要引用外部加载器)
  4. plugins: 插件,能执行范围更广的任务(打包,压缩)
  5. mode:模式 (development开发模式、production生产模式)

其他关联模块

Webpack.png

二、生产环境下的webpack.config.js 基本配置如下:

引入插件、处理loader 复用,定义出口、入口、配置loader、配置plugin、 mode类型。

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

// 复用 loader ,使用ES6 语法,数组...剩余参数
const commonCssLoader = [

    MiniCssExtractPlugin.loader,  // 提取css为单独文件
    'css-loader',
    {
        // /************** (1)需要在package.json 中定义browserslist******/ 
        loader: 'postcss-loader',
        options: {
            idents: 'postcss-loader',
            plugins: () => [require('postcss-preset-env')()]
        }
    }
]

module.exports = {
    extry : './src/index.js',
    output: {
        filename: 'js/bulit.js',
        path: resolve(__dirname, 'build'),
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [...commonCssLoader]
            },
            {
                test: /\.less$/,
                use: [...commonCssLoader,'less-loader']
            },
            /**
             * 正常一个文件只能被一个loader处理,
             * 当一个文件需要被多个loader处理,那么一定要指定loader执行的顺序
             * 先执行eslint 再执行babel
             */
            
            // eslint 的处理
            { 
                // /******(2)在package.json 中 eslintConfig --> airbnb*******/
                test: /\.js$/,
                exclude: /node_modules/,
                // 先执行的属性pre
                enforce: 'pre',
                loader: 'eslint-loader',
                options: {
                    fix:true
                }
            },
            // Babel转换的 处理
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                options: {
                    presets: [
                        '@babel/preset-env',
                        {
                            useBuiltIns: 'usage',
                            corejs: {version:3},
                            targets: {
                                chrome: '60',
                                firefox: '50'
                            }
                        }
                    ]
                }
            },
            {
                test: /\.(jpg|png|gif)/,
                loader: 'url-loader',
                options: {
                    limit: 8*1024,
                    name: '[hash:10].[ext]',
                    outputPath: 'imgs',
                    // 关闭默认的ES6 的解析,用commonjs 的格式
                    esModule: false,
                }
            },
            {
                test: /\.html$/,
                loader: 'html-loader'
            },
            // 其他文件的处理
            {
                exclude: /\.(js|css|less|html|jpg|png|gif|)/,
                loader:'file-loader',
                options: {
                    outputPath: 'media'
                }
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html',
            minify: {
                // 压缩处理,处理空格
                collapseWhitespace: true,
                // 处理 清除注释
                removeComments: true
            }
        }),
        new MiniCssExtractPlugin({
            filename: 'css/built.css'
        }),
        new OptimizeCssAssetsWebpackPlugin()

    ],
    // mode: 'development',  //开发环境
    mode: 'production' // 生产环境
}

三、在package.json 的配置代码

这里是一些依赖文件


{
  "name": "webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "css-loader": "^4.0.0",
    "html-loader": "^2.1.2",
    "html-webpack-plugin": "^4.0.0",
    "less": "^4.1.1",
    "less-loader": "^8.0.0",
    "mini-css-extract-plugin": "^2.1.0",
    "style-loader": "^3.1.0"
  },
  "browserslist": {
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ],
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ]
  },
  "eslintConfig": {
    "extends": "airbnb-base"
  }
}

上面的browserlisteslintConfig可以单独创建文件如下

四、browserslist 配置

分为开发环境和生产环境的浏览器配置

  1. development开发环境中,兼容各个厂商浏览器的最后一个版本
  2. production 生产环境兼容浏览器的种类大于0.2%, 兼容的浏览器是活的
 "browserslist": {
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ],
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ]
  },
  

五、eslintConfig 配置

这个文件一般是eslintrc.js

上面的webpack打包配置中我们只用到了extends这一项的配置

"eslintConfig": {
    "extends": "airbnb-base"
  }

下面这个是比较完整的eslintrc.js 配置文件

module.exports = {
  root: true,
  env: {
    browser: true,
    es6: true,
    node: true,
    jest: true,
  },
  plugins: ['vue'],
  extends: ['plugin:vue/vue3-essential', '@vue/airbnb'],
  rules: {
    'vue/custom-event-name-casing': 'off',
    'vue/no-deprecated-slot-attribute': 'off',
    'vue/experimental-script-setup-vars': 'off',
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-shadow': 0,
    camelcase: [0, { properties: 'always' }],
    'no-plusplus': 0, // 禁止使用++,--
    'guard-for-in': 0,
    'no-extra-semi': 0, // 和prettier冲突
    'import/extensions': 0, // import不需要写文件扩展名
    semi: ['error', 'never'], // 无分号
    'import/no-unresolved': 0,
    'no-restricted-syntax': 0,
    'no-underscore-dangle': 0, // 无下划线
    'no-restricted-syntax': 0,
    'consistent-return': 'off',
    'max-len': ['error', { code: 200 }],
    'no-use-before-define': 'off',
    'no-prototype-builtins': 'off',
    'class-methods-use-this': 'off',
    'template-curly-spacing': 'off',
    'arrow-parens': ['error', 'as-needed'],
    'comma-dangle': ['error', 'only-multiline'],
    'no-param-reassign': ['error', { props: false }],
    'import/no-extraneous-dependencies': ['error', { devDependencies: ['script/**/*.js'] }],
    indent: [
      'warn',
      2,
      {
        ignoredNodes: ['TemplateLiteral'],
        SwitchCase: 1,
      },
    ],
    'object-curly-newline': [
      'error',
      {
        ImportDeclaration: 'never',
      },
    ],
  },
  parserOptions: {
    parser: 'babel-eslint',
  },
}

更多配置项,可查看官方文档 eslintConfig 配置

webpack 相关面试题

5.16..jpg