Webpack4 常用配置详解

作者: Adoins | 来源:发表于2019-04-19 23:10 被阅读0次

    入口、出口配置

    实现Webpack的打包最基本的就是配置好入口、出口,npm install webpack后在根目录创建webpack.config.js,代码如下:

    const path = require('path');
    
    module.exports = {
      entry: { // 也可以直接写成entry: './src/index.js',默认入口就是main别名的index.js文件
        main: './src/index.js' // 指把index.js设为入口文件并且设置别名为main
      },
      output: {
        publicPath: '/', // 也可以不指定,默认为根目录
        filename: '[name].js', // 这里[name]为占位符,即为变量,这里指复用入口文件的名字main
        path: path.resolve(__dirname, 'dist') // 输出文件路径,必须是绝对路径,因此引用node的path模块
      }
    }
    
    

    SourceMap配置

    Webpack打包后如果文件出错会把错误指向打包后的文件中的某一行,而我们更需要知道是源文件哪一行出错,这时就需要配置source-map ,在moudule.exports加入以下配置项

    mode: 'development', // 表示是开发环境,js文件不压缩,设为 production 生产环境 则会压缩
    devtool: 'cheep-module-eval-source-map' // 开发环境的最佳配置
    //devtool: 'cheep-module-source-map', 生产环境的source-map的最佳配置
    
    

    devtool配置项中

    • cheep表示只具体到某一行不具体到某一列,且不检测loader的错误,有助于加快编译速度;
    • module 检测loader的错误,因此错误更全,方便快速查找错误 ;
    • eval表示soucemap的映射代码放到打包后的js文件中,而不是生成source.map.js文件;
    • souce-map指将错误映射到具体源文件上

    热加载

    当希望更改源文件时能自动重新打包文件有两种方法,第一种是在package.json里配置scripts

    scripts: {
      watch: 'webpack --watch'
    } 
    
    

    即可实现效果,缺点是还是得手动刷新页面,不够智能化,因此推荐的事第二种方法,使用webpack-dev-servernpm install webpack-dev-server后,增加配置项:

    devServer: {
      contentBase: './dist', // 设置实时监听打包文件的目录
      open: true, // 自动打开浏览器
      port: 8080, // 端口
      hot: true, // 启动模块热更新
      hotOnly: true // 当模块热更新失败时浏览器也不自动刷新
      // proxy 可以配置跨域
    }
    
    

    当需要更改css文件时页面不刷新,则需要设置hot,启动HotModuleReplacement:先引入webpack模块:const webpack = require('webpck'),再引入插件

    plugins: [
      new webpack.HotModuleReplacementPlugin()
    ]
    
    

    之后在package.json里配置启动脚本

    "scripts": {
      "start": 'webpack-dev-server'
    } 
    
    

    运行npm run start即可热加载网页

    识别打包 js 文件,编译 es6

    当打包 js文件时需要配置模块规则识别

    module: {
      rules: [{
         test: /\.js$/,
         exclude: /node_modules/, // 忽略依赖插件目录的识别
         loader: 'babel-loader' // 但需要编译es6语法时需要引入babel
      }]
    }
    
    

    编译es6用的babel需要在根目录创建配置文件,.babelrc

    {
      presets: [
        [
         "@babel/preset-env", {
           targets: {
             chrome: "67" // 谷歌浏览器自动编译es6语法,因此不用babel转换
           },
           useBuiltIns: "usage" // 按需引入map、Promise等低版本浏览器没有的对象
        }]
      ]
    }
    
    

    IE低版本浏览器中是没有mapPromise等对象的,因此需要借用@babel/polyfill,npm install @babel/preset-env @babel/polyfill -D,之后在js文件中import "@babel/polyfill"即可,但有时我们开发开源组件时不希望polyfill污染全局变量,这是就需要另外一种配置方案,npm install -D @babel/plugin-transform-runtime @babel/runtime-corejs2 ,更改.babelrc配置为

    {
      "plugins": [
         [
           "@babel/plugin-transform-runtime", {
             "corejs": 2, // 设为2才可以引入map等对象
             "helpers": true,
             "regenerator": true,
             "useESModules": false 
           }
         ]
      ]
    }
    
    

    识别打包图片、字体

    npm install -D url-loader file-loader,两个loader均有将图片添加到dist目录里的功能。增加模块识别规则:

    module: {
      rules: [
        {
          test: /\.(jpg|png|gif)$/,
          use: {
            loader: 'url-loader', // 功能跟file-loader差不多,区别是有转换base64的功能
            options: {
              name: '[name]_[hash].[ext]', // ext 是保留源文件后缀
              outputPath: 'images/', // dist 目录下的images文件夹
              limit: 10240 // 10kb以下的图片自动转换为base64编码插入到html中,其他正常生成图片
            }
          }
        }, {
          test: /\.(eot/ttf/svg)$/,
          use: {
            loader: 'file-loader'
          }
        }
      ]
    }
    
    

    识别打包css、scss文件

    npm i -D css-loader style-loader sass-loader postcss-loader ,添加模块识别规则:

    module: {
      rules: [
        {
          test: /\.scss$/,
          use: [ // 从下至上,从右到左执行loader
            'style-loader',  // 将 css 插入到style标签中
        {
          loader: 'css-loader', // 解析css文件,包括对应引用关系
          options: {
            importLoaders: 2
          }
            },
        'sass-loader', // 解析sass,注意安装的时候要安装node-sass,sass-loader
        'postcss-loader' // 添加css前缀,要有postcss.config.js配置上插件
          ]
        },
        {
          test: /\.css$/,
          use: [
            'style-loader',
            'css-loader',
            'postcss-loader'
          ]
        }
      ]
    }
    
    

    postcss.config.js代码如下

    module.exports = {
      plugins: [
        require('autoprefixer')
      ]
    }
    
    

    生成 html

    为了打包后自动生成html文件并引入打包的js文件,需要安装另一个插件,npm i -D html-webpack-plugin ,引入插件const HtmlWebpackPlugin = require('html-webpack-plugin'),增加插件配置项

    plugins: [
      new HtmlWebpackPlugin({
        template: 'src/index.html' // 引用html模板,之后生成的html则会按照此模板生成并且自动引入打包后的js文件
      })
    ]
    
    

    打包前自动清除dist目录

    打包前最好能自动清除dist 目录,防止冗余文件,npm i -D clean-webpack-plugin,引入插件const CleanWebpackPlugin = require('clean-webpack-plugn'),添加插件配置

    plugins: [
      new CleanWebpackPlugin(['dist'])
    ]
    
    

    编译 React 代码文件

    npm i --save react react-dom后即可编写React代码

    import React, { Component } from 'react'
    import ReactDom from 'react-dom'
    
    class App extends Component {
      render() {
        return <div>Hello World</div>
      }
    }
    
    ReactDom.render(<App />, document.getElementById('root'))
    

    编译React代码则还需要npm i --save @babel/preset-react,并在.babelrc中的presets数组里增加一项"@babel/preset-react"即可正常编译

    总结

    webpack.config.js的完整代码如下:

    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const CleanWebpackPlugin = require('clean-webpack-plugin');
    const webpack = require('webpack');
    module.exports = {
            mode: 'development',
            devtool: 'cheep-module-eval-source-map',
        entry: {
            main: './src/index.js',
        },
            devServer: {
                    contentBase: './dist',
                    open: true,
                    port: 8080,
                    hot: true,
                    hotOnly: true
            },
        module: {
            rules: [{ 
                test: /\.js$/, 
                exclude: /node_modules/,
                    loader: 'babel-loader'
            }, {
                test: /\.(jpg|png|gif)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        name: '[name]_[hash].[ext]',
                        outputPath: 'images/',
                        limit: 10240
                    }
                } 
            }, {
                test: /\.(eot|ttf|svg)$/,
                use: {
                    loader: 'file-loader'
                } 
            },
                    {
                            test: /\.scss$/,
                            use: [ // 从下至上,从右到左执行loader
                                    'style-loader',  // 将 css 插入到style标签中
                                {
                                       loader: 'css-loader', // 解析css文件,包括对应引用关系
                                       options: {
                                             importLoaders: 2
                                       }
                                    },
                                'sass-loader', // 解析sass,注意安装的时候要安装node-sass,sass-loader
                                'postcss-loader' // 添加css前缀,要有postcss.config.js配置上插件
                           ]
                    },
                    {
                           test: /\.css$/,
                           use: [
                                    'style-loader',
                                    'css-loader',
                                    'postcss-loader'
                           ]
                    }]
        },
        plugins: [
            new HtmlWebpackPlugin({
                template: 'src/index.html'
            }), 
            new CleanWebpackPlugin(['dist']),
            new webpack.HotModuleReplacementPlugin()
        ],
        output: {
                    filename: '[name].js',
            path: path.resolve(__dirname, 'dist')
        }
    }
    
    

    相关文章

      网友评论

        本文标题:Webpack4 常用配置详解

        本文链接:https://www.haomeiwen.com/subject/mlyhgqtx.html