• weback5基础配置详解


    1、安装

    命令:

    npm init -y
    npm install webpack webpack-cli --save-dev
    
    • 1
    • 2

    在项目的根目录下启动 cmd,执行 webpack 命令会出现不是内部或外部命令(因为是本地安装),可以执行以下命令构建:

    npx webpack
    
    • 1

    2、配置

    webpack.config.js配置文件

    在项目根目录下创建 webpack.config.js 文件,配置内容如下:

    const path = require('path')
    
    module.exports = {
      entry: './src/index.js',
      output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, './dist')
      },
      mode: 'development'
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    package.json 中配置 npm script 脚本:

    {
      "scripts": {
        "build": "webpack"
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    此时,打包命令如下:

    npm run build
    
    • 1

    插件

    html-webpack-plugin 为例,安装:

    npm install html-webpack-plugin --save-dev
    
    • 1

    webpack.config.js 文件添加以下配置:

    const HtmlWebpackPlugin = require('html-webpack-plugin')
    
    module.exports = {
       output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, './dist'),
        clean: true  // 清除旧的打包文件
      },
      plugins: [
        new HtmlWebpackPlugin({
        	template: './index.html', // 模板位置
          	filename: 'index.html', // 打包后的html文件名称
          	inject: 'body' // script标签位置,可选值:body/head
        })
      ]
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    需要在项目根目录创建 index.html 模板文件。

    设置 mode 模式

    开发模式

    module.exports = {
        mode: 'development'
    }
    
    • 1
    • 2
    • 3

    生产模式

    module.exports = {
        mode: 'production'
    }
    
    • 1
    • 2
    • 3

    区别:开发模式打包的 .js 文件没有压缩,并且显示详细信息;开发模式打包的 .js 文件是压缩后的文件

    源代码调试

    代码异常时定位到源码,在 webpack.config.js 文件中配置:

    module.exports = {
    	devtool: 'inline-source-map'
    }
    
    • 1
    • 2
    • 3

    devtool 字段的模式包括:

    模式说明
    eval每个 module 会封装到 eval 里包裹起来执行,并且会在末尾追加注释 //@ sourceURL
    source-map生成一个 SourceMap 文件
    inline-source-map生成一个 DataURL 形式的 SourceMap 文件
    hidden-source-mapsource-map 一样,但不会在 bundle 末尾追加注释
    eval-source-map每个 module 会通过 eval() 来执行,并且生成一个 DataURL 形式的 SourceMap
    cheap-source-map生成一个没有列信息(column-mappings)的 SourceMaps 文件,不包括 loadersourcemap (譬如 babelsourcemap
    cheap-module-source-map生成一个没有列信息(column-mappings)的 SourceMap 文件,同时 loadersourcemap 也被简化为只包含对应行的

    动态编译

    修改 package.json 中的 npm script 脚本:

    {
        “scripts”: {
            "build": "webpack --watch"
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    本地服务器

    安装:

    npm install webpack-dev-server --save-dev
    
    • 1

    配置 npm script

    {
        "scripts": {
            "dev": "webpack-dev-server",
        	"build": "webpack --watch"
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    启动服务:

    npm run dev
    
    • 1

    在浏览器中访问项目 http://127.0.0.1:8080/

    配置默认打开浏览器:

    {
        "scripts": {
            "dev": "webpack-dev-server --open",
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    webpack.config.js 文件配置本地服务器:

    const path = require('path')
    
    module.exports = {
        devServer: {
            static: path.resolve(__dirname, './dist'),
            compress: true, // 服务器端是否进行代码压缩,传输 zip 压缩包
            port: 8080, // 端口号
            host: '0.0.0.0', // 
            headers: { // 配置响应头
                'X-Access-Token': 'xxx'
            },
            proxy: {
                '/api': {
                    target: 'http://192.168.1.100:3000', // 真实的服务器地址
                    pathRewrite: {
                      '^/api': ''
                    }
                 }
            },
            https: { // 配置HTTPS证书
              cacert: './server.pem',
              pfx: './server.pfx',
              key: './server.key',
              cert: './server.crt',
              passphrase: 'webpack-dev-server',
              requestCert: true
            },
            historyApiFallback: true, // 配置 SPA 应用的 history 路由模式
            hot: true, // 模块热替换
            liveReload: true, // 开启热更新
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    加载资源

    (1)resource资源

    // webpack.config.js
    
    module.exports = {
      output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, './dist'),
        clean: true,
        assetModuleFilename: 'image/[contenthash][ext]'  // 自定义静态资源打包目录与名称
      },
      module: {
        rules: [
          {
            test: /\.jpg|\.png$/,
            type: 'asset/resource',  // 发送一个单独文件的URL
            generator: {
              filename: 'images/[contenthash][ext]'  // 优先级高于 output.assetModuleFilename
            }
          }
        ]
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    (2)inline资源

    不会打包出任何静态资源文件

    // webpack.config.js
    
    module.exports = {
      module: {
        rules: [
          {
            test: /\.jpg|\.png$/,
            type: 'asset/inline'  // 导出一个资源的Data URI,页面中的图片为 base64
          }
        ]
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    (3)source资源

    不会打包出任何静态资源文件

    // webpack.config.js
    
    module.exports = {
      module: {
        rules: [
          {
            test: /\.txt$/,
            type: 'asset/source'  // 导出资源的源代码
          }
        ]
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    通用资源类型 asset,在导出一个 data URI 和发送一个单独的文件之间自动选择。

    默认地,当文件小于 8kb 时,将会被视为 inline 模块类型,否则会被视为 resource 模块类型。可以在 module rule 层级中,设置 Rule.parser.dataUrlCondition.maxSize 选项来修改条件。修改配置文件:

    // webpack.config.js
    
    module.exports = {
      module: {
        rules: [
          {
            test: /\.jpg$/,
            type: 'asset',
            parser: {
              dataUrlCondition: {
                maxSize: 200 * 1024 // 小于200kb是为 inline 模式
              }
            }
          }
        ]
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    加载CSS

    需要安装 css 相关的 loader

    npm install css-loader style-loader --save-dev
    
    • 1

    css-loader 用于编译 css 文件,style-loader 用于将 css 代码加载到 .html 模板文件中。

    配置文件:

    // webpack.config.js
    
    module.exports = {
        module: {
            rules: [
                {
                    test: /\.css$/,
                    use: ['style-loader', 'css-loader'] // loader执行顺序为逆向加载(数组元素的倒序)
                }
            ]
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    在项目中引入 sass,安装 sasssass-loader

    npm install sass sass-loader --save-dev
    
    • 1

    修改配置文件:

    // webpack.config.js
    
    module.exports = {
        module: {
            rules: [
                {
                    test: /\.(css|scss)$/,
                    use: ['style-loader', 'css-loader', 'sass-loader'] // loader执行顺序为逆向加载(数组元素的倒序)
                }
            ]
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    要以模块化的方式将 .css.scss 样式文件引入 .js 文件中

    抽离 CSS

    需要安装插件:

    npm install mini-css-extract-plugin --save-dev
    
    • 1

    mini-css-extract-plugin 插件最小支持 webpack5 版本

    修改配置文件:

    // webpack.config.js
    
    const MiniCssExtractPlugin = require('mini-css-extract-plugin')
    module.exports = {
        plugins: [
            new MiniCssExtractPlugin({
                filename: 'style/[contenthash].css'
            })
        ],
        module: {
            rules: [
                {
                    test: /\.(css|scss)$/,
                    use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
                }
            ]
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    压缩 CSS

    安装插件:

    npm install css-minimizer-webpack-plugin --save-dev
    
    • 1

    修改配置文件:

    // webpack.config.js
    
    const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
    module.exports = {
      mode: 'production',
      optimization: {
        minimizer: [
          new CssMinimizerPlugin()
        ]
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    配置完成后,执行构建命令 npm run build, 打包后的 css 代码就被压缩了。

    加载 fonts 字体

    修改配置文件:

    // webpack.config.js
    
    module.exports = {
        module: {
            rules: [
                {
                    test: /\.(woff|woff2|eot|ttf|otf)$/,
                    type: 'asset/resource'
                }
            ]
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    加载数据

    (1)加载 csvtsv 文件

    安装:

    npm install csv-loader --save-dev
    
    • 1

    修改配置文件:

    // webpack.config.js
    
    module.exports = {
        module: {
            rules: [
                {
                    test: /\.(csv|tsv)$/,
                    use: ['csv-loader']
                }
            ]
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    (2)加载 xml 文件

    安装:

    npm install xml-loader --save-dev
    
    • 1

    修改配置文件:

    // webpack.config.js
    
    module.exports = {
        module: {
            rules: [
                {
                    test: /\.xml$/,
            		use: ['xml-loader']
                }
            ]
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    (3)加载 yaml 文件

    安装依赖:

    npm install yaml --save-dev
    
    • 1

    修改配置文件:

    // webpack.config.js
    
    const yaml = require('yaml')
    module.exports = {
        module: {
            rules: [
                {
                    test: /\.yaml$/,
            		type: 'json',
                    parser: {
                      parse: yaml.parse
                    }
                }
            ]
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    (4)加载 toml 文件

    安装依赖:

    npm install toml --save-dev
    
    • 1

    修改配置文件:

    // webpack.config.js
    
    const toml = require('toml')
    module.exports = {
        module: {
            rules: [
                {
                    test: /\.toml$/,
            		type: 'json',
                    parser: {
                      parse: toml.parse
                    }
                }
            ]
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    (5)加载 json5 文件

    webpack 默认可以编译 json 文件,如果使用了升级版的 .json5 文件,需要安装依赖:

    npm install json5 --save-dev
    
    • 1

    修改配置文件:

    // webpack.config.js
    
    const json5 = require('json5')
    module.exports = {
        module: {
            rules: [
                {
                    test: /\.json5$/,
            		type: 'json',
                    parser: {
                      parse: json5.parse
                    }
                }
            ]
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    ES6ES5

    ES6 代码转为 ES5 代码需要 babel-loader 加载器,其中:

    • babel-loader:在 webpack 中应用 babel 解析 ES6 的桥梁;
    • @babel/corebabel 核心模块;
    • @babel/preset-envbabel 预设,一组 babel 插件的集合。

    安装:

    npm install babel-loader @babel/core @babel/preset-env --save-dev
    
    • 1

    修改配置文件:

    // webpack.config.js
    
    module.exports = {
        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: /node_modules/,
            		use: {
                      loader: 'babel-loader',
                      options: {
                        presets: ['@babel/preset-env']
                      }
                    }
                }
            ]
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    还需要再安装 regeneratorRuntime 插件,它是 webpack 打包生成的全局辅助函数,有 babel 生成,用于兼容 async/await 语法。
    安装插件:

    # 生产环境运行时需要这个插件,要安装到生产环境依赖
    npm install @babel/runtime --save
    
    # 编译时需要在使用 regeneratorRuntime 的地方自动 require 导包
    npm install @babel/plugin-transform-runtime --save-dev
    
    • 1
    • 2
    • 3
    • 4
    • 5

    修改配置文件:

    // webpack.config.js
    
    module.exports = {
        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: /node_modules/,
            		use: {
                      loader: 'babel-loader',
                      options: {
                        presets: ['@babel/preset-env'],
                        plugins: [
                            ['@babel/plugin-transform-runtime']
                        ]
                      }
                    }
                }
            ]
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    配置 eslint

    安装 eslint

    npm install eslint --save-dev
    
    • 1

    初始化 .eslintrc 文件,执行以下命令自定生成:

    npx eslint --init
    
    • 1

    在控制台中选择如下:

    $ npx exlint --init
    √ How would you like to use ESLint? · style
    √ What type of modules does your project? · esm
    √ Which framework does your project use? · none
    √ Does your project use TypeScript? · No
    √ Where does your code run? · browser
    √ How would you like to dofine a sytle for your project? · guide
    √ Which style guide do you want to follow? · airbnb
    √ What format do you want your config file to be in? · JSON
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    .eslintrc 文件的默认配置如下:

    • env:设置脚本的运行环境;
    • extends:继承社区整理好的配置规则,例如 eslint-plugin-react/recommended 使用社区的 react 规则;
    • plugins:添加的插件,为 eslint 增加新的检查规则,例如 eslint-plugin-react 是对 react 项目的检查规则;
    • parser:配置解析项目的规则,例如 @typescript-eslint/parser
    • parserOptions:搭配 parser ,指定需要支持的 javascript 语言选项;
    • globals:当访问当前源文件内未定义的变量时,no-undef 规则将发出警告。如果你想在一个源文件里使用全局变量,推荐你在 ESLint 中定义这些全局变量,这样 ESLint 就不会发出警告了;readonly 表示可读不可写,writable 表示可读可写;
    • rules:具体的规则,off 或 0 表示关闭规则;warn 或 1 表示使用警告级别开启规则(不会退出程序);error 或 2 表示使用错误级别开启规则(触发规则会退出程序)。

    结合 webpack 使用

    安装:

    npm install eslint-loader --save-dev
    
    • 1

    修改 webpack.config.js 文件:

    module.exports = {
        module: {
            rules: [
                {
                    test: /\.(js | jsx)$/,
                    exclude: /node_modules/,
                    use: ['babel-loader', 'eslint-loader']
                }
            ]
        },
        devServer: {
            client: {
                overlay: true // 默认为true,即开启热更新功能
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
  • 相关阅读:
    365天深度学习训练营-学习线路
    【多媒体文件格式】AVI、WAV、RIFF
    边云协同架构设计
    dubbo发送过程编码失败,会唤醒发送线程吗?
    【PAT(甲级)】1072 Gas Station
    二叉树详解(求二叉树的结点个数、深度、第k层的个数、遍历等)
    LightGBM使用教程
    Spring Cloud(四):Spring Cloud Alibaba Feign & Dubbo
    分布式运用之企业级日志ELFK+logstash的过滤模块
    ClickHouse删除数据之delete问题详解
  • 原文地址:https://blog.csdn.net/p445098355/article/details/125519102