likes
comments
collection
share

webpack4配置vue开发环境

作者站长头像
站长
· 阅读数 16

本文写于 2019.06.25 10:11 webpack4升级webpack5后大部分都还可用,后续有空更新

本文总结Webpack4常见的配置。 1、基础配置(让项目跑起来) 2、webpack处理css 3、webpack处理sass文件 4、webpack为sass添加source map 5、webpack为css添加CSS3前缀 6、抽离样式表为单独的css文件并打版本号 7、webpack压缩CSS 8、webpack压缩js 9、webpack添加页面模板 10、webpack清理打包后的dist目录 11、webpack处理图片 12、webpack压缩图片 13、webpack把小图片转为base64 14、webpack处理文字 15、webpack配置js使用sourceMap 16、webpack开启热更新和代理配置 17、webpack启用babel转码 18、alias对文件路径优化 19、使用happypack并发执行任务 案例中自带不细说: 1、定义全局变量 2、合并提取webpack公共配置 3、使用静态资源路径publicPath(CDN)

1、基础配置

让项目跑起来 项目初始化: npm init 安装webpack、vue、与vue-loader: npm i webpack vue vue-loader -D webpack4 已经启用webpack-cli : npm i webpack-cli -s -d 解析.vue文件,与内联css: npm i css-loader vue-template-compiler -D 并按照下面目录构建项目 webpack4配置vue开发环境 app.vue

    <template>
        <div> luckfine </div>
    </template>
    <script>
        export default {
            data () {
                //text: 'luckfine'
            }
        }
    </script>
    <style>
    </style>

index.js

    // index.js
    import Vue from 'vue'
    import App from '../components/app.vue'

    const root = document.createElement('div')
    document.body.appendChild(root)

    new Vue({
        render: (h) => h(App)
    }).$mount(root)

webpack.js

    // webpack.js
    const path = require('path')
    const VueLoaderPlugin = require('vue-loader/lib/plugin');

    module.exports = {
        entry:  path.join(__dirname, 'src/spa/index.js'),
        mode:'develop',
        output: {
            filename: 'bundle.js',
            path: path.join(__dirname, 'dist')
        },
        module: {
            rules: [
                {
                    test: /.vue$/,
                    loader: 'vue-loader'
                }
            ]
        },
        plugins:[
            new VueLoaderPlugin()
        ],
    }

在package.json 文件里的scripts对象里面添加一个脚本: (注意:webpack4中已经在启动时用mode指定启动环境)

     "scripts": {
        "build": "webpack --config webpack.config.js --mode=development"
      },

webpack4配置vue开发环境

让我们的spa项目先跑起来

    npm install webpack-dev-server -s -d

    npm install html-webpack-plugin -d -s

// webpack.config.js

const path = require('path')
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry:  path.join(__dirname, 'src/h5/pages/demo.js'),
    mode:'develop',
    output: {
        filename: 'bundle.js',
        path: path.join(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /.vue$/,
                loader: 'vue-loader'
            }
        ]
    },
    resolve: {
        extensions: [
          '.vue', '.js'
        ],
        modules: ["node_modules"],
        alias: {
          vue: 'vue/dist/vue.min.js',
          components: path.resolve(__dirname + '/src/components/'),
          '@': path.resolve('src')
        }
    },
    plugins:[
        new HtmlWebpackPlugin(),
        new VueLoaderPlugin()
    ],
    devServer: {
        historyApiFallback: {
          index: `/dist/h5/index.html`
        },
        host: '0.0.0.0',
        disableHostCheck: true
    }
}

添加项目快捷启动

"dev": "webpack-dev-server --inline --hot --mode=development",

npm run dev

webpack4配置vue开发环境

项目已经跑起来了,开始webpack的配置

2、webpack处理css

npm i -D css-loader style-loader

//  webpack.config.js
    module: {
        rules: [
            {
                test: /.vue$/,
                loader: 'vue-loader'
            },
            {
                test: /\.css/,
                use: ['style-loader', 'css-loader'] // use的顺序从右往左
            }
        ]
    },

webpack4配置vue开发环境

3、webpack处理sass文件

npm install sass-loader node-sass -D

        module: {
            rules: [
                {
                    test: /.vue$/,
                    loader: 'vue-loader'
                },
                {
                    test: /\.(sc|sa|c)ss$/,
                    use: ['style-loader', 'css-loader', 'sass-loader'] // use的顺序从右往左
                }
            ]
        },

webpack4配置vue开发环境

4、webpack为sass添加source map

webpack4配置vue开发环境

                {
                    test: /\.(sc|sa|c)ss$/,
                    use: [
                        {
                            loader: 'style-loader'
                        },
                        {
                            loader: 'css-loader',
                            options: {
                                sourceMap: true
                            }
                        },
                        {
                            loader: 'sass-loader',
                            options: {
                                sourceMap: true
                            }
                        }
                    ]
                }

添加后

webpack4配置vue开发环境

5、webpack为css添加CSS3前缀

npm i -D postcss-loader autoprefixer postcss

在刚才的index.css 加上display: flex; 根目录新建一个postcss.config.js

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

<!---->

        module: {
            rules: [
                {
                    test: /.vue$/,
                    loader: 'vue-loader'
                },
                {
                    test: /\.(sc|sa|c)ss$/,
                    use: [
                        {
                            loader: 'style-loader'
                        },
                        {
                            loader: 'css-loader',
                            options: {
                                sourceMap: true
                            }
                        },
                        {
                            loader: 'postcss-loader'
                        },
                        {
                            loader: 'sass-loader',
                            options: {
                                sourceMap: true
                            }
                        }
                    ]
                }
            ]
        },

webpack4配置vue开发环境

6、抽离样式表为单独的css文件并打版本号

npm install webpack-merge -s -d
npm i -D mini-css-extract-plugin
    //webpack.prod.config.js
    const merge = require('webpack-merge')
    const webpack = require('webpack');
    const baseConfig = require('./webpack.config.js')
    const MiniCssExtractPlugin = require('mini-css-extract-plugin')
    const devMode = process.env.NODE_ENV !== 'production'


    module.exports = merge(baseConfig, {
        module: {
            rules: [
                {
                    test: /\.(sc|sa|c)ss$/,
                    use: [
                    	MiniCssExtractPlugin.loader,
                        {
                            loader: 'style-loader'
                        },
                        {
                            loader: 'css-loader',
                            options: {
                                sourceMap: true
                            }
                        },
                        {
                            loader: 'postcss-loader'
                        },
                        {
                            loader: 'sass-loader',
                            options: {
                                sourceMap: true
                            }
                        }
                    ]
                }
            ]
        },
        plugins: [
            new MiniCssExtractPlugin({
                filename: devMode ? '[name].css' : '[name].[hash:8].css', 
                chunkFilename: devMode ? '[id].css': '[id].[hash:8].css'
            })
        ]
    })

"dist": "webpack --config webpack.prod.config.js --mode=production",

webpack4配置vue开发环境

7、webpack压缩CSS

npm i -D optimize-css-assets-webpack-plugin

        optimization: {
            minimizer: [
                // 压缩CSS
                new OptimizeCSSAssertsPlugin({})
            ]
        },

webpack4配置vue开发环境

8、webpack压缩js

`npm i -D uglifyjs-webpack-plugin`

    const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

        optimization: {
            minimizer: [
                // 压缩CSS
                new OptimizeCSSAssertsPlugin({}),
                // 压缩JS
                new UglifyJsPlugin({
                    // 有很多可以配置
                    cache: true,
                    parallel: true,
                    sourceMap: true,
                    uglifyOptions: {
                         // 在UglifyJs删除没有用到的代码时不输出警告
                        warnings: false,
                        output: {
                            // 删除所有的注释
                            comments: false,
                            // 最紧凑的输出
                            beautify: false
                        },
                        compress: {
                            // 删除所有的 `console` 语句
                            // 还可以兼容ie浏览器
                            drop_console: true,
                            // 内嵌定义了但是只用到一次的变量
                            collapse_vars: true,
                            // 提取出出现多次但是没有定义成变量去引用的静态值
                            reduce_vars: true,
                        }
                    }
                })
            ]
        },

webpack4配置vue开发环境

Uglify-js不支持es6语法,请使用terser插件, 于是我们更改使用terser插件试试, 其实你继续用uglifyjs-webpack-plugin也可以, 只需要配合babel先转下。

    const TerserPlugin = require('terser-webpack-plugin');
        optimization: {
            minimizer: [
                // 压缩CSS
                new OptimizeCSSAssertsPlugin({}),
                // 压缩JS
                new TerserPlugin({
                    cache: true,
                    parallel: true,
                    sourceMap: true
                })
            ]
        },

更多配置见官网terser-webpack-plugin

webpack4配置vue开发环境

9、webpack添加页面模板

html-webpack-plugin插件可以把js/css注入到一个模板文件, 所以不需要再手动更改引用。 创建一个模板

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
        <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
        <meta name="format-detection" content="telephone=no">
        <title><%= htmlWebpackPlugin.options.title %></title>
    </head>
    <body>
    	
    </body>
    </html>

// webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin')

plugins: [
    // 打包模板
        new HtmlWebpackPlugin({
            inject: true,
            hash: true,
            cache: true,
            chunksSortMode: 'none',
            title: '页面模板', // 可以由外面传入
            filename: 'index.html', // 默认index.html
            template: 'src/spa/index.html',
            minify: {
                collapseWhitespace: true,
                removeComments: true,
                removeRedundantAttributes: true,
                removeScriptTypeAttributes: true,
                removeStyleLinkTypeAttributes: true
            }
        }),
],

webpack4配置vue开发环境

10、webpack清理打包后的dist目录

npm i -D clean-webpack-plugin

    const { CleanWebpackPlugin } = require('clean-webpack-plugin');

    plugins:[
            new CleanWebpackPlugin()
    ]

11、webpack处理图片

            {
                test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            limit: 1,
                            name: '[name].[hash].[ext]'
                        },
                    },
                ]
            }

webpack4配置vue开发环境

12、webpack压缩图片

npm i -D image-webpack-loader

                {
                    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                    use: [
                        {
                            loader: 'file-loader',
                            options: {
                                limit: 1,
                                name: '[name].[hash].[ext]'
                            },
                        },
                        {
                            loader: 'image-webpack-loader',
                            options: {
                              mozjpeg: {
                                progressive: true,
                                quality: 65
                              },
                              // optipng.enabled: false will disable optipng
                              optipng: {
                                enabled: false,
                              },
                              pngquant: {
                                quality: '65-90',
                                speed: 4
                              },
                              gifsicle: {
                                interlaced: false,
                              },
                              // the webp option will enable WEBP
                              webp: {
                                quality: 75
                              }
                            }
                        }
                    ]
              }

目前图片112kb,压缩后31kb

13、webpack把图片转为base64

npm i -D url-loader

                {
                    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                    use: [
                        {
                            loader: 'url-loader',
                            options: {
                                // 具体配置见插件官网
                                limit: 10000,
                                name: '[name]-[hash:5].[ext]'
                            },
                        },
                        {
                            loader: 'image-webpack-loader',
                            options: {
                              mozjpeg: {
                                progressive: true,
                                quality: 65
                              },
                              // optipng.enabled: false will disable optipng
                              optipng: {
                                enabled: false,
                              },
                              pngquant: {
                                quality: '65-90',
                                speed: 4
                              },
                              gifsicle: {
                                interlaced: false,
                              },
                              // the webp option will enable WEBP
                              webp: {
                                quality: 75
                              }
                            }
                        }
                    ]
                },

webpack4配置vue开发环境

14、webpack处理文字

{
    test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
    loader: 'url-loader',
    options: {
        // 文件大小小于limit参数,url-loader将会把文件转为DataUR
        limit: 10000,
        name: '[name]-[hash:5].[ext]',
        output: 'fonts/'
    }
},

15、webpack配置js使用sourceMap

devtool: 'inline-source-map'

16、webpack开启热更新和代理配置

    devServer: {
        clientLogLevel: 'warning', // 输出日志级别
        hot: true, // 启用热更新
        contentBase: path.resolve(__dirname, 'dist'), // 告诉服务器从哪里提供内容
        publicPath: '/', // 此路径下的打包文件可在浏览器下访问
        compress: true, // 启用gzip压缩
        // publicPath: './',
        disableHostCheck: true,
        host: '0.0.0.0',
        port: 8080,
        open: true, // 自动打开浏览器
        overlay: { // 出现错误或者警告时候是否覆盖页面线上错误信息
            warnings: true,
            errors: true
        },
        quiet: true,
        watchOptions: { // 监控文件相关配置
            poll: true,
            ignored: /node_modules/, // 忽略监控的文件夹, 正则
            aggregateTimeout: 300, // 默认值, 当你连续改动时候, webpack可以设置构建延迟时间(防抖)
        }
    },

webpack启用babel转码 npm i -D babel-loader @babel/core @babel/preset-env @babel/runtime @babel/plugin-transform-runtime

    // 编译js
    {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
            loader: 'babel-loader?cacheDirectory', // 通过cacheDirectory选项开启支持缓存
            options: {
              presets: ['@babel/preset-env']
            }
        }
    },

添加.babelrc文件


// 仅供参考
{
    "presets": [
      [
        "@babel/preset-env"
      ]
    ],
    "plugins": [
      [
        "@babel/plugin-transform-runtime",
        {
          "corejs": false,
          "helpers": true,
          "regenerator": true,
          "useESModules": false,
          "absoluteRuntime": "@babel/runtime"
        }
      ]
    ]
  }

18、alias对文件路径优化

配置alias方便路径的检索效率。 加快模块的查找速度

       resolve: {
            extensions: ['.vue', '.js'],
            modules: ['node_modules'],
            alias: {
              components: __dirname + '/src/components/',
              assets: __dirname + '/src/assets/'
            }
        },

19、使用happypack并发执行任务

在 Loader 配置中,所有文件的处理都交给了 happypack/loader 去处理,使用紧跟其后的 querystring ?id=babel 去告诉 happypack/loader 去选择哪个 HappyPack 实例去处理文件。


const HappyPack = require('HappyPack')
const os = require('os');
const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length });

{
    test: /\.js$/,
    exclude: /(node_modules|bower_components)/,
    use: [
        {
            // 一个loader对应一个id
            loader: "happypack/loader?id=luckfine"
        }
    ]
},

 
new HappyPack({
      // 用唯一的标识符id,来代表当前的HappyPack是用来处理一类特定的文件
      id:'luckfine',
        //如何处理  用法和loader 的配置一样
      loaders: [{
        loader: 'babel-loader?cacheDirectory=true',
      }],
      //共享进程池
      threadPool: happyThreadPool,
      //允许 HappyPack 输出日志
      verbose: true,
}),
转载自:https://juejin.cn/post/7235485148417130556
评论
请登录