更新4.x版本webpack,并升级相关插件
npm i -D webpack@latest
npm i -D webpack-bundle-analyzer@latest webpack-merge@latest webpack-dev-server@latest
UglifyJsPlugin报错—>webpack4.x写法改变
报错:
D:\workspace\zy-evst-platform\node_modules\webpack\lib\webpack.js:189
throw new RemovedPluginError(errorMessage);
^
Error: webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead.
at Object.get [as UglifyJsPlugin] (D:\workspace\zy-evst-platform\node_modules\webpack\lib\webpack.js:189:10)
.......
解决: 修改为下面这种形式
optimization: {
minimizer: [new UglifyJsPlugin({
uglifyOptions: {
warnings: false,
mangle: true,
compress: {
pure_funcs: ['console.log']
}
}
})]
},
CommonsChunkPlugin 报错 —>webpack4 移除了 CommonsChunkPlugin,需要修改配置
报错:
D:\workspace\zy-evst-platform\node_modules\webpack\lib\webpack.js:189
throw new RemovedPluginError(errorMessage);
^
Error: webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead.
解决: 修改为下面这种形式(optimization中添加)
splitChunks: {
cacheGroups: {
commons: {
name: "commons",
chunks: "initial",
minChunks: 2
}
}
}
HtmlWebpackPlugin报错 —>需要升级
报错:
- building for production...D:\workspace\zy-evst-platform\node_modules\html-webpack-plugin\lib\compiler.js:81
var outputName = compilation.mainTemplate.applyPluginsWaterfall('asset-path', outputOptions.filename, {
^
TypeError: compilation.mainTemplate.applyPluginsWaterfall is not a function
at D:\workspace\zy-evst-platform\node_modules\?[4mhtml-webpack-plugin?[24m\lib\compiler.js:81:51
at D:\workspace\zy-evst-platform\node_modules\?[4mwebpack?[24m\lib\Compiler.js:343:11
解决:
npm i -D html-webpack-plugin@latest
ExtractTextPlugin —> 使用mini-css-extract-plugin来替换extract-text-webpack-plugin
报错:
Error: Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead
at Chunk.get (D:\workspace\zy-evst-platform\node_modules\?[4mwebpack?[24m\lib\Chunk.js:866:9)
at D:\workspace\zy-evst-platform\node_modules\?[4mextract-text-webpack-plugin?[24m\dist\index.js:176:48
解决:注意有两个配置文件需要修改, 并且别忘了删除extract-text-webpack-plugin相关的配置哦
npm i -D mini-css-extract-plugin
webpack.conf.js中:
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
plugins: [
new MiniCssExtractPlugin({
filename: utils.assetsPath('css/[name].css'),
chunkFilename: utils.assetsPath('css/[name].[contenthash].css')
})
]
build/utils.js
修改前的报错:
ERROR in ./src/assets/css/global.scss
Module build failed (from ./node_modules/extract-text-webpack-plugin/dist/loader.js):
Error: "extract-text-webpack-plugin" loader is used without the corresponding plugin, refer to https://github.com/webpack/extract-text-webpack-plugin for the usage example
at Object.pitch (D:\workspace\zy-evst-platform\node_modules\extract-text-webpack-plugin\dist\loader.js:57:11)
@ ./src/main.js 8:0-34
ERROR in ./src/assets/css/layout.scss
Module build failed (from ./node_modules/extract-text-webpack-plugin/dist/loader.js):
Error: "extract-text-webpack-plugin" loader is used without the corresponding plugin, refer to https://github.com/webpack/extract-text-webpack-plugin for the usage example
at Object.pitch (D:\workspace\zy-evst-platform\node_modules\extract-text-webpack-plugin\dist\loader.js:57:11)
@ ./src/main.js 9:0-34
解决:
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
if (options.extract) {
// 此处修改为:
return [MiniCssExtractPlugin.loader].concat(loaders)
} else {
return ['vue-style-loader'].concat(loaders)
}
更新一些loader
npm i -D vue-loader@latest vue-style-loader@latest
又报错啦:
You may need an additional loader to handle the result of these loaders.
解决:****(vue-loader更新为15x版本以后,webpack.base.conf.js中配置需要改)
const {
VueLoaderPlugin } = require('vue-loader')
plugins: [
new VueLoaderPlugin()
]
// 原来的注释掉
// const vueLoaderConfig = require('./vue-loader.conf')
{
test: /\.vue$/,
loader: 'vue-loader',
// 这个注释掉!!
// options: vueLoaderConfig
},
更新一些插件
npm i -D compression-webpack-plugin@latest friendly-errors-webpack-plugin@latest optimize-css-assets-webpack-plugin@latest
配置mode webpack.base.conf.js module.exports中:
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
HtmlWebpackPlugin 配置需要修改
报错:
UnhandledPromiseRejectionWarning: Error: "dependency" is not a valid chunk sort mode
解决:
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
},
// chunksSortMode: 'dependency' // 这里注释掉!!!
}),
修改配置后的webpack.conf.js文件
'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const env = require('../config/prod.env')
const webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
optimization: {
minimizer: [new UglifyJsPlugin({
uglifyOptions: {
warnings: false,
mangle: true,
compress: {
pure_funcs: ['console.log']
}
}
})],
splitChunks: {
cacheGroups: {
commons: {
name: "commons",
chunks: "initial",
minChunks: 2
}
}
}
},
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: 'server',
analyzerHost: '127.0.0.1',
analyzerPort: 8989,
defaultSizes: 'parsed',
openAnalyzer: false,
generateStatsFile: false,
statsFilename: 'stats.json',
statsOptions: null,
logLevel: 'info'
}),
new webpack.DefinePlugin({
'process.env': env
}),
new MiniCssExtractPlugin({
filename: utils.assetsPath('css/[name].css'),
chunkFilename: utils.assetsPath('css/[name].[contenthash].css')
}),
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? {
safe: true, map: {
inline: false } }
: {
safe: true }
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
// favicon: path.resolve('src/assets/images/favicon.ico'),
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
},
// chunksSortMode: 'dependency'
}),
new webpack.HashedModuleIdsPlugin(),
new webpack.optimize.ModuleConcatenationPlugin(),
]
})
if (config.build.productionGzip) {
const CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
修改后的webpack.base.conf.js文件
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
// const vueLoaderConfig = require('./vue-loader.conf')
const {
VueLoaderPlugin } = require('vue-loader')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
context: path.resolve(__dirname, '../'),
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
plugins: [
new VueLoaderPlugin()
],
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
}
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
// options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},
{
test: /\.svg$/,
loader: 'svg-sprite-loader',
include: [resolve('src/assets/icons')],
options: {
symbolId: 'icon-[name]'
}
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
exclude: resolve('src/assets/icons'),
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
node: {
// prevent webpack from injecting useless setImmediate polyfill because Vue
// source contains it (although only uses it if it's native).
setImmediate: false,
// prevent webpack from injecting mocks to Node native modules
// that does not make sense for the client
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}
'use strict'
const path = require('path')
const config = require('../config')
// const ExtractTextPlugin = require('extract-text-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const packageConfig = require('../package.json')
exports.assetsPath = function (_path) {
const assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory
return path.posix.join(assetsSubDirectory, _path)
}
exports.cssLoaders = function (options) {
options = options || {
}
const cssLoader = {
loader: 'css-loader',
options: {
sourceMap: options.sourceMap
}
}
const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap
}
}
// generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({
}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
// Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
return [MiniCssExtractPlugin.loader].concat(loaders)
} else {
return ['vue-style-loader'].concat(loaders)
}
}
// https://vue-loader.vuejs.org/en/configurations/extract-css.html
return {
css: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
sass: generateLoaders('sass', {
indentedSyntax: true }),
scss: generateLoaders('sass'),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
}
// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
const output = []
const loaders = exports.cssLoaders(options)
for (const extension in loaders) {
const loader = loaders[extension]
output.push({
test: new RegExp('\\.' + extension + '$'),
use: loader
})
}
return output
}
exports.createNotifierCallback = () => {
const notifier = require('node-notifier')
return (severity, errors) => {
if (severity !== 'error') return
const error = errors[0]
const filename = error.file && error.file.split('!').pop()
notifier.notify({
title: packageConfig.name,
message: severity + ': ' + error.name,
subtitle: filename || '',
icon: path.join(__dirname, 'logo.png')
})
}
}
{
"name": "evst-platform",
"version": "1.0.0",
"description": "evst control mangement system",
"author": "LeeHongxiao <[email protected]>",
"private": true,
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"analyz": "cross-env NODE_ENV=production npm_config_report=true npm run build",
"start": "npm run dev",
"build": "node build/build.js",
"test": "node build/test.js",
"develop": "node build/develop.js"
},
"dependencies": {
"axios": "^0.19.0",
"dayjs": "^1.8.17",
"echarts": "^4.5.0",
"element-ui": "^2.13.0",
"i18n": "^0.8.4",
"json-bigint": "^0.3.0",
"jsonwebtoken": "^8.5.1",
"jwt-decode": "^2.2.0",
"nprogress": "^0.2.0",
"svg-sprite-loader": "^4.1.6",
"vue": "^2.6.10",
"vue-count-to": "^1.0.13",
"vue-i18n": "^8.15.1",
"vue-router": "^3.0.6",
"vuex": "^3.1.0"
},
"devDependencies": {
"autoprefixer": "^7.1.2",
"babel-core": "^6.22.1",
"babel-helper-vue-jsx-merge-props": "^2.0.3",
"babel-loader": "^7.1.1",
"babel-plugin-syntax-jsx": "^6.18.0",
"babel-plugin-transform-runtime": "^6.22.0",
"babel-plugin-transform-vue-jsx": "^3.5.0",
"babel-preset-env": "^1.3.2",
"babel-preset-stage-2": "^6.22.0",
"chalk": "^2.0.1",
"compression-webpack-plugin": "^4.0.0",
"copy-webpack-plugin": "^6.0.3",
"css-loader": "^0.28.0",
"extract-text-webpack-plugin": "^3.0.0",
"file-loader": "^1.1.4",
"friendly-errors-webpack-plugin": "^1.7.0",
"html-webpack-plugin": "^4.3.0",
"mini-css-extract-plugin": "^0.9.0",
"node-notifier": "^5.1.2",
"node-sass": "^4.13.0",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"ora": "^1.2.0",
"portfinder": "^1.0.13",
"postcss-import": "^11.0.0",
"postcss-loader": "^2.0.8",
"postcss-url": "^7.2.1",
"rimraf": "^2.6.0",
"sass-loader": "^7.0.3",
"semver": "^5.3.0",
"shelljs": "^0.7.6",
"uglifyjs-webpack-plugin": "^1.1.1",
"url-loader": "^0.5.8",
"vue-loader": "^15.9.3",
"vue-style-loader": "^4.1.2",
"vue-template-compiler": "^2.5.2",
"webpack": "^4.43.0",
"webpack-bundle-analyzer": "^3.8.0",
"webpack-dev-server": "^3.11.0",
"webpack-merge": "^4.2.2"
},
"engines": {
"node": ">= 6.0.0",
"npm": ">= 3.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}