基于vue-cli 将webpack3 升级到 webpack4 配置
升级webpack4前 先删除之前的webpack, babel-loader
下载 webpack
npm i -D webpack@4 webpack-cli@3 webpack-dev-server@3
下载 plugins
npm i -D babel-polyfill happypack html-webpack-plugin clean-webpack-plugin progress-bar-webpack-plugin yargs-parser friendly-errors-webpack-plugin portfinder webpack-merge extract-text-webpack-plugin@next optimize-css-assets-webpack-plugin uglifyjs-webpack-plugin chalk rimraf
下载 babel-loader
npm i babel-loader @babel/cli @babel/core @babel/ @babel/preset-env plugin-proposal-class-properties @babel/ plugin-proposal-decorators @babel/ plugin-syntax-dynamic-import @babel/plugin-transform-classes @babel/plugin-transform-runtime -D
npm i --save @babel/runtime @babel/runtime-corejs2
{
"presets": [
["@babel/preset-env", {
"useBuiltIns": "usage"
}]
],
"plugins": [
["@babel/plugin-proposal-decorators", {
"legacy": true
}],
"@babel/proposal-class-properties",
["@babel/plugin-transform-runtime", {
"corejs": 2
}],
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-transform-classes"
]
}
配置build文件夹下的文件:
build.js webpack.base.conf.js webpack.dev.conf.js webpack.pro.conf.js
webpack.base.conf.js 配置以下内容
const os = require('os') //node OS模块 可查看主机系统相关信息
const path = require('path') //node path模块 c处理文件路径
const utils = require('./utils') //vue-cli封装的公用模块
const webpack = require('webpack')
const config = require('../config')//vue-cli封装的配置
const HappyPack = require("happypack")//开启多个子进程去并发执行
const HtmlWebpackPlugin = require('html-webpack-plugin')//webpack主要插件,可以简化HTML文件的创建
const CleanWebpackPlugin = require('clean-webpack-plugin');//清空打包好的文件
const ProgressBarPlugin = require('progress-bar-webpack-plugin')//查看进度
const vueLoaderConfig = require('./vue-loader.conf')// 处理less,sass等样式配置文件
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const argv = require("yargs-parser")(process.argv.slice(2))//获取运行 scripts 里面的指令 --mode 后面参数
const isPro = argv.mode == "production"
const resolve = dir => path.resolve(__dirname, "..", dir) module.exports = {
context: path.resolve(__dirname, '../'),
entry: {
app: ['babel-polyfill', './src/main.js']
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: isPro ?
config.build.assetsPublicPath : config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue': 'vue/dist/vue.esm.js',
'src': path.resolve(__dirname, '../src/common'),
'@': resolve('src'),
'~': resolve('src/components/common'),
'static': path.resolve(__dirname, '../static'),
}
},
module: {
rules: [{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loaders: 'happypack/loader?id=babel',//配合 happypack插件使用
exclude: /(node_modules|bower_components)/,
include: [resolve('src'), resolve('test')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
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: {
setImmediate: false,
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
},
plugins: [
new ProgressBarPlugin(),
new CleanWebpackPlugin(),
new HappyPack({
id: 'babel',
loaders: [{
loader: 'babel-loader',
options: {
babelrc: true,
cacheDirectory: true,
},
publicPath: "/"
}],
//共享进程池
threadPool: HappyPack.ThreadPool({
size: os.cpus().length //cpu nunbers
}),
//允许 HappyPack 输出日志
verbose: true,
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify(argv.mode)
}
}),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true,
favicon: './src/assets/img/favicon.ico'
}),
new webpack.ProvidePlugin({//引入全局变量
$: 'jquery',
jQuery: 'jquery', // 加上这个
}), new VueLoaderPlugin()
]
}
webpack.dev.conf.js 配置以下内容 (开发环境)
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')//可以合并 base.conf 配置文件
const baseWebpackConfig = require('./webpack.base.conf')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')//让日志更加友好
const portfinder = require('portfinder') //查找开放端口或域接字的简单工具 const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
const devWebpackConfig = merge(baseWebpackConfig, {
mode:'development',
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
devtool: config.dev.devtool, devServer: {
clientLogLevel: 'warning',
historyApiFallback: true,
hot: true,
compress: true,
host: HOST || config.dev.host,
port: PORT || config.dev.port,
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay
? { warnings: false, errors: true }
: false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable,
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll,
},
disableHostCheck: true
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
}) module.exports = new Promise((resolve, reject) => {
portfinder.basePort = process.env.PORT || config.dev.port
portfinder.getPort((err, port) => {
if (err) {
reject(err)
} else {
process.env.PORT = port
devWebpackConfig.devServer.port = port // Add FriendlyErrorsPlugin
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
})) resolve(devWebpackConfig)
}
})
})
webpack.prod.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 CopyWebpackPlugin = require('copy-webpack-plugin')//复制文件和目录
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')//提取样式文件,只有extract-text-webpack-plugin@^4.0.0-beta.0 才支持webpack4
//或者使用 mini-css-extract-plugin 用法详见 
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') //用于优化\最小化 CSS
const UglifyJsPlugin = require('uglifyjs-webpack-plugin') // 压缩JS资源
const webpackConfig = merge(baseWebpackConfig, {
mode: 'production',
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: {
splitChunks: {
chunks: 'all', // initial、async和all
minSize: 30000, // 形成一个新代码块最小的体积
maxAsyncRequests: 5, // 按需加载时候最大的并行请求数
maxInitialRequests: 3, // 最大初始化请求数
automaticNameDelimiter: '~', // 打包分割符
name: true
}, minimizer: [ new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[hash].css'),
allChunks: true,
}),
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap ? {
safe: true,
map: {
inline: false
}
} : {
safe: true
}
}),
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
inject: true,
favicon: './src/assets/img/favicon.ico',
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true }, chunksSortMode: 'dependency'
}), new webpack.optimize.ModuleConcatenationPlugin(), new CopyWebpackPlugin([{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}])
] }
}) module.exports = webpackConfig
'use strict'
require('./check-versions')() process.env.NODE_ENV = 'production' const rm = require('rimraf')//删除文件
const path = require('path')
const chalk = require('chalk')//终端字符串样式
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf') rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, (err, stats) => { if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n') if (stats.hasErrors()) {
console.log(chalk.red(' 构建失败,错误.\n'))
process.exit(1)
} console.log(chalk.cyan(' Build success.\n'))
console.log(chalk.yellow(
' 打包文件应通过HTTP服务器启用.\n'
))
})
})
package.js (npm 配置)
"scripts": {
"dev": "webpack-dev-server --inline --mode development -- config build/webpack.dev.conf.js",
"build": "node build/build.js "
},
基于vue-cli 将webpack3 升级到 webpack4 配置的更多相关文章
- 基于vue cli 3.0创建前端项目并安装cube-ui
前提条件: 安装node.js. 国内的开发者最好先配置淘宝镜像. 之后用cnpm来代替npm命令. 项目创建过程: 打开cmd,输入命令进入目标工作空间,以本机项目为例: cd /d d: cd D ...
- 基于@vue/cli 的构建项目(3.0)
1.检测node的版本号 注意:1.Vue CLI需要Node.js的版本 8.9+(推荐8.11.0+) 所以在安装Vue CLI之前先看下node的版本 node -v 2.安装@vue/cli ...
- @vue/cli 3.x项目脚手架 webpack 配置
@vue/cli 是一个基于 Vue.js 进行快速开发的完整系统. @vue/cli 基于node服务 需要8.9以上版本 可以使用 nvm等工具来控制node版本 构建于 webpack ...
- 基于Vue cli生成的Vue项目的webpack4升级
前面的话 本文将详细介绍从webpack3到webpack4的升级过程 概述 相比于webpack3,webpack4可以零配置运行,打包速度比之前提高了90%,可以直接到ES6的代码进行无用代码剔除 ...
- webpack3升级为webpack4
写在前面的话:为什么要升级,因为公司目前的项目使用webpack3,但是因为是多页应用,入口估计有一百多个,开发模式下慢得不像话,修改一个文件需要十几秒才编译好,之前的解决方案是减少入口,但是要调试其 ...
- 记录一次webpack3升级到webpack4过程
升级之前也参考了一些网上的教程.借鉴之,进行的自己的升级.一些版本为什么设为那个版本号也是参考别人的结果. 整体是按照先升级npm run dev:在升级npm run build的顺序. 首先升级w ...
- 基于vue现有项目的服务器端渲染SSR改造
前面的话 不论是官网教程,还是官方DEMO,都是从0开始的服务端渲染配置.对于现有项目的服务器端渲染SSR改造,特别是基于vue cli生成的项目,没有特别提及.本文就小火柴的前端小站这个前台项目进行 ...
- Vue CLI 3+tinymce 5富文本编辑器整合
基于Vue CLI 3脚手架搭建的项目整合tinymce 5富文本编辑器,vue cli 2版本及tinymce 4版本参考:https://blog.csdn.net/liub37/article/ ...
- vue cli 平稳升级webapck4
webpack4 released 已经有一段时间了,插件系统趋于平稳,适逢对webpack3的打包速度很不满意,因此决定将当前在做的项目进行升级,正好也实践一下webpack4. 新特性 0配置 应 ...
随机推荐
- Linux定时任务(crond)
1.Crond定义 crond是Linux系统中用来定期执行命令或指定程序的一种服务或软件. (1)linux系统自身定期执行的任务(轮询系统日志.备份数据等) (2)用户执行的任务(定时更新同步时间 ...
- luogu2658 GCD(莫比乌斯反演/欧拉函数)
link 给定整数N,求1<=x,y<=N且Gcd(x,y)为素数的数对(x,y)有多少对. 1<=N<=10^7 (1)莫比乌斯反演法 发现就是YY的GCD,左转YY的GCD ...
- 改变iOS app的icon(iOS10.3)
原文 改变iOS app的icon官方iOS10.3新增了可以让开发者去更改app的icon,接下来看看怎么更改.官方API给的东西很少,只是介绍了一个实例方法: 1 open func setAlt ...
- node 后台搭建笔记
*注:本文是个人记录,非常粗略 1.建立server服务的文件被单独放置在一个文件夹下或最外层 2.src文件包含:controller/model/routes 文件夹 和 app.js文件
- kuangbin专题十二 HDU1074 Doing Homework (状压dp)
Doing Homework Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)To ...
- PHP删除目录下的空目录
function rm_empty_dir($path){ if(is_dir($path) && ($handle = opendir($path))!==false){ ...
- linux 虚拟环境问题
1.python环境 python2和python3命令用来区分python版本 pip2和pip3命令用来区分pip,你的包到底安装在哪里pip3 install xxx sudo apt inst ...
- linux上传与下载
首先必须安装xshell这个工具 使用xshell来操作服务非常方便,传文件也比较方便.就是使用rz,sz首先,服务器要安装了rz,szyum install lrzsz当然你的本地windows主机 ...
- 解决dubbo注册zookepper服务IP乱入问题的三种方式
最近做一个项目引入了dubbo+zookepper的分布式服务治理框架.在应用的发布的时候出现一个怪问题.zookepper服务是起在开发服务器192.168.23.180上.本机起应用服务提供者注册 ...
- 对DeepLung数据预处理部分的详细展示
之前有解释预处理部分的函数,不过觉得还不够详细,同时文字解释还不够直观,所以现在想一步步运行下,打印输出 首先读取原始数据,包括相应的注释(即结节标签)[注意]注释文件中的标签是按x,y,z的顺序给的 ...