使用webpack搭建vue工程

276 阅读2分钟

最近看了一个慕课的免费课程,Vue+Webpack打造todo应用,此处应有课程链接www.imooc.com/learn/935

这个课程干货满满,小白知道了开发项目第一步可以不使用vue-cli搭建,但是唯一让我觉得痛苦的就是老师使用的webpack不是最新的(目前更新到"webpack": "^4.39.3"),然后就是一系列的爬坑之行。

最新版webpack构建的vue项目代码下载 github.com/typsxxn/Vue…

接下来我就盘点一下vue webpack npm run dev/build遇到的所有的坑以及解决方法:

1. 

Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead

错误原因:webpack是版本4,而extract-text-webpack-plugin使用3版本不支持

解决方法:升级extract-text-webpack-plugin

                npm i extract-text-webpack-plugin@next

2.

 Error: Path variable [contentHash:8] not implemented in this context: styles.[contentHash:8].css 

错误原因:webpack4以上打包css不支持contentHash<也有人说原因是webpack4.x中提取CSS文件应该使用mini-css-extract-plugin,废弃extract-text-webpack-plugin,详参juejin.cn/post/684490…>

解决方法:把contentHash 改写为 chunkHash,可以run build

3. 

webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead. 

(webpack.optimize.CommonsChunkPlugin被移除)

错误原因:webpack4版本以上 把 webpack.optimize.CommonsChunkPlugin 这个类移除了 换成了splitChunks

解决方法:抄作业,修改如下:

config.plugins.push(        
new ExtractPlugin('styles.[chunkHash:8].css'),    
)
config.optimization = {
        splitChunks: {
            cacheGroups: { // 设置缓存的 chunks
                commons: { 
                   chunks: 'initial', // 必须三选一: "initial" | "all" | "async"(默认异步)
                    minSize: 0, // 最小尺寸,默认0,
                    minChunks: 2, // 最小 chunk ,默认1
                    maxInitialRequests: 5 // 最大初始化请求书,默认1
                },
                vendor: {
                    test: /node_modules/, // 正则规则验证,如果符合就提取 chunk
                    chunks: 'initial', // 必须三选一: "initial" | "all" | "async"(默认异步)
                    name: 'vendor', // 要缓存的 分隔出的 chunk 名称
                    priority: 10, // 缓存组优先级
                    enforce: true
                }
            }
        },
        runtimeChunk: true
    }

4.

Module Error (from ./node_modules/vue-loader/lib/index.js):
vue-loader was used without the corresponding plugin. Make sure to include VueLoaderPlugin in your 
webpack config.
......

错误原因:VueLoaderPlugin 插件没引,webpack4配置需要包含VueLoaderPlugin

解决方法:

plugins: [        new webpack.DefinePlugin({            'process.env': {                NODE_ENV: isDev ? '"development"' : '"production"'            }        }),        new HTMLPlugin(),        new VueLoaderPlugin()    ]


参考博文:blog.csdn.net/a578024797/…

                blog.csdn.net/MessageBox_…

侵删