vue-cli webpack配置文件分析
相信vue使用者对vue-cli都不会陌生,甚至可以说,很熟悉了,但对其webpack的配置可能知之甚少吧。
过完年回来后,我接手了公司的新项目。新项目是一个spa。很自然,我就想到了vue-cli脚手架了,当时研究一下它的webpack配置。于是,就有了其他的内容。
今天这篇文章,是在原来的基础上,增加了一些新版本的内容,但实质上变化不大。
说明
此仓库为vue-cli webpack的配置分析,其实只是在源码中加上注释而已。大家查看详细分析,可以从后面提到的入口文件开始查看。
分析不包括check-versions.js文件,因为check-versions.js是检测npm和node版本,不涉及webpack,所以就没有对check-versions.js进行分析。同时,也不包括测试部分的代码,该分析只是针对开发和生产环境的webpack配置进行分析。
vue-cli 版本
2.8.1
入口
从package.json可以看到开发和生产环境的入口。
"scripts": {
"dev": "node build/dev-server.js",
"build": "node build/build.js"
}
开发环境
开发环境的入口文件是 build/dev-server.js。
dev-server.js
该文件中,使用express作为后端框架,结合一些关于webpack的中间件,搭建了一个开发环境。
// 配置文件
var config = require('../config')
// 如果 Node 的环境无法判断当前是 dev / product 环境
// 使用 config.dev.env.NODE_ENV 作为当前的环境
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
}
// 可以强制打开浏览器并跳转到指定 url 的插件
// https://github.com/sindresorhus/opn
var opn = require('opn')
// node自带的文件路径工具
var path = require('path')
// express框架
var express = require('express')
var webpack = require('webpack')
// 测试环境,使用的配置与生产环境的配置一样
// 非测试环境,即为开发环境,因为此文件只有测试环境和开发环境使用
var proxyMiddleware = require('http-proxy-middleware')
var webpackConfig = process.env.NODE_ENV === 'testing'
// 生产环境配置文件
"htmlcode">
// 工具函数集合
var utils = require('./utils')
var webpack = require('webpack')
// 配置文件
var config = require('../config')
// webpack 配置合并插件
var merge = require('webpack-merge')
// webpac基本配置
var baseWebpackConfig = require('./webpack.base.conf')
// 自动生成 html 并且注入到 .html 文件中的插件
// https://github.com/ampedandwired/html-webpack-plugin
var HtmlWebpackPlugin = require('html-webpack-plugin')
// webpack错误信息提示插件
// https://github.com/geowarin/friendly-errors-webpack-plugin
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// 将 Hol-reload 热重载的客户端代码添加到 webpack.base.conf 的 对应 entry 中,一起打包
Object.keys(baseWebpackConfig.entry).forEach(function(name) {
baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})
module.exports = merge(baseWebpackConfig, {
module: {
// styleLoaders
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
},
// 最新的配置为 cheap-module-eval-source-map,虽然 cheap-module-eval-source-map更快,但它的定位不准确
// 所以,换成 eval-source-map
devtool: '#eval-source-map',
plugins: [
// definePlugin 接收字符串插入到代码当中, 所以你需要的话可以写上 JS 的字符串
// 此处,插入适当的环境
// https://webpack.js.org/plugins/define-plugin/
new webpack.DefinePlugin({
'process.env': config.dev.env
}),
// HotModule 插件在页面进行变更的时候只会重绘对应的页面模块,不会重绘整个 html 文件
// https://github.com/glenjamin/webpack-hot-middleware#installation--usage
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
// 将 index.html 作为入口,注入 html 代码后生成 index.html文件
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
// webpack错误信息提示插件
new FriendlyErrorsPlugin()
]
})
webpack.base.conf.js
在webpack.dev.conf.js中出现webpack.base.conf.js,这个文件是开发环境和生产环境,甚至测试环境,这些环境的公共webpack配置。可以说,这个文件相当重要。
// node自带的文件路径工具
var path = require('path')
// 工具函数集合
var utils = require('./utils')
// 配置文件
var config = require('../config')
// 工具函数集合
var vueLoaderConfig = require('./vue-loader.conf')
/**
* 获得绝对路径
* @method resolve
* @param {String} dir 相对于本文件的路径
* @return {String} 绝对路径
*/
function resolve(dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
app: './src/main.js'
},
output: {
// 编译输出的静态资源根路径
path: config.build.assetsRoot,
// 编译输出的文件名
filename: '[name].js',
// 正式发布环境下编译输出的上线路径的根路径
publicPath: process.env.NODE_ENV === 'production' "pre",
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
},
{
// 处理 vue文件
// https://github.com/vuejs/vue-loader
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
// 编译 js
// https://github.com/babel/babel-loader
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},
{
// 处理图片文件
// https://github.com/webpack-contrib/url-loader
test: /\.(png|jpe"htmlcode">
// 详情见文档:https://vuejs-templates.github.io/webpack/env.html
var path = require('path')
module.exports = {
// production 生产环境
build: {
// 构建环境
env: require('./prod.env'),
// 构建输出的index.html文件
index: path.resolve(__dirname, '../dist/index.html'),
// 构建输出的静态资源路径
assetsRoot: path.resolve(__dirname, '../dist'),
// 构建输出的二级目录
assetsSubDirectory: 'static',
// 构建发布的根目录,可配置为资源服务器域名或 CDN 域名
assetsPublicPath: '/',
// 是否开启 cssSourceMap
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
// 默认关闭 gzip,因为很多流行的静态资源主机,例如 Surge、Netlify,已经为所有静态资源开启gzip
productionGzip: false,
// 需要使用 gzip 压缩的文件扩展名
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
// 运行“build”命令行时,加上一个参数,可以在构建完成后参看包分析报告
// true为开启,false为关闭
bundleAnalyzerReport: process.env.npm_config_report
},
// dev 开发环境
dev: {
// 构建环境
env: require('./dev.env'),
// 端口号
port: 3333,
// 是否自动打开浏览器
autoOpenBrowser: true,
assetsSubDirectory: 'static',
// 编译发布的根目录,可配置为资源服务器域名或 CDN 域名
assetsPublicPath: '/',
// proxyTable 代理的接口(可跨域)
// 使用方法:https://vuejs-templates.github.io/webpack/proxy.html
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
// 默认情况下,关闭 CSS Sourcemaps,因为使用相对路径会报错。
// CSS-Loader README:https://github.com/webpack/css-loader#sourcemaps
cssSourceMap: false
}
}
utils.js
utils.js也是一个被使用频率的文件,这个文件包含了三个工具函数:
- 生成静态资源的路径
- 生成 ExtractTextPlugin对象或loader字符串
- 生成 style-loader的配置
// node自带的文件路径工具
var path = require('path')
// 配置文件
var config = require('../config')
// 提取css的插件
// https://github.com/webpack-contrib/extract-text-webpack-plugin
var ExtractTextPlugin = require('extract-text-webpack-plugin')
/**
* 生成静态资源的路径
* @method assertsPath
* @param {String} _path 相对于静态资源文件夹的文件路径
* @return {String} 静态资源完整路径
*/
exports.assetsPath = function (_path) {
var assetsSubDirectory = process.env.NODE_ENV === 'production'
"htmlcode">
// 设置当前环境为生产环境
process.env.NODE_ENV = 'production'
// loading 插件
// https://github.com/sindresorhus/ora
var ora = require('ora')
// 可以在 node 中执行`rm -rf`的工具
// https://github.com/isaacs/rimraf
var rm = require('rimraf')
// node自带的文件路径工具
var path = require('path')
// 在终端输出带颜色的文字
// https://github.com/chalk/chalk
var chalk = require('chalk')
var webpack = require('webpack')
// 配置文件
var config = require('../config')
var webpackConfig = require('./webpack.prod.conf')
// 在终端显示loading效果,并输出提示
var spinner = ora('building for production...')
spinner.start()
// 删除这个文件夹 (递归删除)
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
// 构建
webpack(webpackConfig, function (err, stats) {
// 构建成功
// 停止 loading动画
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
// 打印提示
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
})
webpack.prod.conf
该文件,为生产环境中webpack的配置入口。同时,它也依赖于前面提到的webpack.base.conf.js、utils.js和config/index.js。
// node自带的文件路径工具
var path = require('path')
// 工具函数集合
var utils = require('./utils')
var webpack = require('webpack')
// 配置文件
var config = require('../config')
// webpack 配置合并插件
var merge = require('webpack-merge')
// webpack 基本配置
var baseWebpackConfig = require('./webpack.base.conf')
// webpack 复制文件和文件夹的插件
// https://github.com/kevlened/copy-webpack-plugin
var CopyWebpackPlugin = require('copy-webpack-plugin')
// 自动生成 html 并且注入到 .html 文件中的插件
// https://github.com/ampedandwired/html-webpack-plugin
var HtmlWebpackPlugin = require('html-webpack-plugin')
// 提取css的插件
// https://github.com/webpack-contrib/extract-text-webpack-plugin
var ExtractTextPlugin = require('extract-text-webpack-plugin')
// webpack 优化压缩和优化 css 的插件
// https://github.com/NMFR/optimize-css-assets-webpack-plugin
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
// 如果当前环境为测试环境,则使用测试环境
// 否则,使用生产环境
var env = process.env.NODE_ENV === 'testing'
"color: #ff0000">其他
如果你觉得在segmentfault的代码阅读体验不好,你可以到我github上将代码clone下来看。
vue-cli-webpack-analysis
总结
这次研究webpack配置的时候,我自己跟着源码敲了一遍(很笨的方法),然后,在github和webpack官网上查使用到的插件的作用和用法。经过这一次折腾,加深对webpack的认识。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇:vue3.0 搭建项目总结(详细步骤)
下一篇:微信小程序开发之左右分栏效果的实例代码