vue webpack的配置文件还是挺多的,下面是关于此配置的基本目录结构:
config
├── dev.env.js //dev环境变量配置
├── index.js // dev和prod环境的一些基本配置
└── prod.env.js // prod环境变量配置
build
├── build.js // npm run build所执行的脚本
├── check-versions.js // 检查npm和node的版本
├── logo.png
├── utils.js // 一些工具方法,主要用于生成cssLoader和styleLoader配置
├── vue-loader.conf.js // vueloader的配置信息
├── webpack.base.conf.js // dev和prod的公共配置
├── webpack.dev.conf.js // dev环境的配置
└── webpack.prod.conf.js // prod环境的配置
------ package.json //npm 命令行声明
config/index.js:基本配置
'use strict'
// 模板版本: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
// 本地开发环境
dev: {
// 编译生成的静态文件的目录
assetsSubDirectory: 'static',
// 编译发布的根目录,可配置为资源服务器域名或者cdn域名
assetsPublicPath: '/',
// 需要使用proxyTable代理的接口(可以跨域)
proxyTable: {},
// 各种开发服务器设置
host: 'localhost', // 开发时候的访问域名,可以被覆盖 process.env.HOST
port: 1234, // 可以被覆盖process.env.PORT, 如果端口正在使用,将确定一个空闲端口
// 设置项目是否自动打开网页
autoOpenBrowser: false,
//在浏览器是否展示错误蒙层
errorOverlay: true,
// 是否展示错误的通知
notifyOnErrors: true,
// 控制监听文件的选项。
// webpack 使用文件系统来通知文件更改。 在某些情况下,这不起作用。 例如,使用网络文件系统(NFS)时。 Vagrant 也有很多问题。 在这些情况下,请使用轮询:
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
// 是否使用eslint loader去检查代码
useEslint: false,
// 不符合Eslint规则时,false为警告(默认true为运行出错)
showEslintErrorsInOverlay: false,
// 查看文件报错位置的格式,共有13种
// https://webpack.js.org/configuration/devtool/#development
devtool: 'source-map ',
// 是否加上在文件后加上hash,对文件缓存进行清理
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
// 是否关闭css的source map
cssSourceMap: true
},
// 线上环境
build: {
// html生成路径
index: path.resolve(__dirname, '../dist/index.html'),
//编译生成的文件的目录
assetsRoot: path.resolve(__dirname, '../dist'),
// 编译生成的静态文件的目录
assetsSubDirectory: 'static',
// 编译发布的根目录,可配置为资源服务器域名或者cdn域名
assetsPublicPath: '/',
// false是对源码进行压缩加密
productionSourceMap: true,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// 是否开启生产环境的gzip压缩
// 在设置为 `true`之前, 请确认安装npm install --save-dev compression-webpack-plugin
// 此模块最低需要 Node v6.9.0和Webpack v4.0.0);如果达不到,就得降级了,否则会报错
productionGzip: false,
// 开启gzip压缩的文件的后缀名称
productionGzipExtensions: ['js', 'css'],
//运行带有额外参数的build命令
//在生成完成后查看bundle analyzer报告:
// `npm run build --report`
//设置为“true”或“false”以始终打开或关闭它
// 打包文件优化工具 webpack-bundle-analyzer
bundleAnalyzerReport: process.env.npm_config_report
}
}
config/dev.env.js:开发模式的环境变量
'use strict'
// webpack-merge合并数组和对象
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
})
config/prod.env.js:生产模式的环境变量
'use strict'
module.exports = {
NODE_ENV: '"production"'
}
build/vue-loader.conf.js:vue-loader的配置
'use strict'
// vue-loader的一些基本配置
const utils = require('./utils')
const config = require('../config')
// 返回当前模式是否为生产模式
const isProduction = process.env.NODE_ENV === 'production'
// 根据布尔值判断引入不同SourceMap文件
const sourceMapEnabled = isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap
module.exports = {
// vue文件中的css loader配置
loaders: utils.cssLoaders({
sourceMap: sourceMapEnabled,
// 生产环境下就会把css文件抽取到一个独立的文件中
extract: isProduction
}),
cssSourceMap: sourceMapEnabled,
// css source map文件缓存控制变量
cacheBusting: config.dev.cacheBusting,
// preserveWhitespace 减少文件体积,阻止元素间生成空白内容
preserveWhitespace: false,
transformToRequire: {
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: 'xlink:href'
}
}
build/utils.js:各种loader配置
'use strict'
// 引入nodejs的path模块,用于操作路径
const path = require('path')
// 引入模板的配置文件
const config = require('../config')
// 把css代码从js文件中抽离出来,单独出一个模块。
const ExtractTextPlugin = require('extract-text-webpack-plugin')
// 引入package.json文件
const packageConfig = require('../package.json')
// 静态路径
exports.assetsPath = function (_path) {
// 判断所处环境是生产环境还是开发环境,选择设置的静态文件存放目录
const assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory
// path.posix属性提供对 path 方法的 POSIX 特定实现的访问。
return path.posix.join(assetsSubDirectory, _path)
}
// cssloader
exports.cssLoaders = function (options) {
options = options || {}
const cssLoader = {
loader: 'css-loader',
options: {
sourceMap: options.sourceMap
}
}
const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap
}
}
// 生成用于提取文本插件的加载程序字符串
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
})
})
}
//指定该选项时提取CSS
//(生产构建期间就是这样)
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else {
return ['vue-style-loader'].concat(loaders) //concat() 方法用于连接两个或多个数组。
}
}
// 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')
}
}
// 为独立样式文件生成加载程序(在.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')
})
}
}
build/webpack.dev.conf.js:webpack 基本配置
'use strict'
// 引入utils配置文件
const utils = require('./utils')
// 引入webpack模块
const webpack = require('webpack')
//引入 config配置文件
const config = require('../config')
// 引入webpack-merge模块
const merge = require('webpack-merge')
// 引入path模块
const path = require('path')
// 引入本地webpack配置
const baseWebpackConfig = require('./webpack.base.conf')
// 使用copy-webpack-plugin插件进行拷贝不需要参与打包的资源文件到输出目录
const CopyWebpackPlugin = require('copy-webpack-plugin')
// 使用html-webpack-plugin自动打包html插件
const HtmlWebpackPlugin = require('html-webpack-plugin')
// Friendly-errors-webpack-plugin识别某些类别的webpack错误,并清理,聚合和优先级,以提供更好的开发人员体验。
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// portfinder插件帮你自动获取可用端口
const portfinder = require('portfinder')
// 开发模式配置
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
// 为那些独立的css类型文件添加loader配置(没有写在vue文件的style标签中的样式)
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
// 开发环境使用'eval-source-map'模式的source map
devtool: config.dev.devtool,
// 下面是对webpack-dev-server选项的基本配置,这些配置信息,我们可以在/config/index.js
devServer: {
clientLogLevel: 'warning',
historyApiFallback: {
rewrites: [
// 表示当使用html5的history api的时候,任意的404响应都需要被替代为index.html
{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
],
},
// 热更新
hot: true,
// 一切服务都需要使用gzip压缩
contentBase: false,
compress: true,
host: HOST || config.dev.host,
// 指定要监听请求的端口号
port: PORT || config.dev.port,
// 是否打开浏览器
open: config.dev.autoOpenBrowser,
// 当编译出现错误的时候,是否希望在浏览器中展示一个全屏的蒙层来展示错误信息
overlay: config.dev.errorOverlay
// 表示只显示错误信息而不显示警告信息
// 如果两者都希望显示,则把这两项都设置为true
? { warnings: false, errors: true }
: false,
publicPath: config.dev.assetsPublicPath,
// / 配置代理,这样我们就可以跨域访问某些接口
// 我们访问的接口,如果符合这个选项的配置,就会通过代理服务器转发我们的请求
proxy: config.dev.proxyTable,
// 启用 quiet 后,除了初始启动信息之外的任何内容都不会被打印到控制台。这也意味着来自 webpack 的错误或警告在控制台不可见。
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll,
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
new webpack.HotModuleReplacementPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.dev.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
module.exports = new Promise((resolve, reject) => {
portfinder.basePort = process.env.PORT || config.dev.port
portfinder.getPort((err, port) => {
if (err) {
reject(err)
} else {
// 把获取到的端口号设置为环境变量PORT的值
process.env.PORT = port
// 重新设置webpack-dev-server的端口的值
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我们的配置文件
resolve(devWebpackConfig)
}
})
})
build/webpack.base.conf.js:webpack 开发模式下的配置
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')
// 公共配置
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
// webpack解析文件时候的根目录(如果把webpack.config.js)放在了项目的根目录下面,这个配置可以省略
context: path.resolve(__dirname, '../'),
// 指定项目的入口文件
entry: {
app: './src/main.js'
},
// 项目的输出配置
output: {
// 项目build的时候,生成的文件的存放路径(这里的路径是../dist)
path: config.build.assetsRoot,
// 生成文件的名称
filename: '[name].js',
// 输出解析文件的目录,url 相对于 HTML 页面(生成的html文件中,css和js等静态文件的url前缀)
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
// 配置模块解析时候的一些选项
resolve: {
// 指定哪些类型的文件可以引用的时候省略后缀名
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
// 可以在引入文件的时候使用@符号引入src文件夹中的文件
'@': resolve('src'),
}
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},
{
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]')
}
}
]
},
// 这些选项用于配置polyfill或mock某些node.js全局变量和模块。
// 这可以使最初为nodejs编写的代码可以在浏览器端运行
node: {
//阻止网页包注入无用的setfill,因为Vue
//源包含它(尽管只有在它是本机的情况下才使用它)。
setImmediate: false,
//阻止webpack向节点本机模块注入模拟
//这对客户来说毫无意义
// 设置成empty则表示提供一个空对象
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}
build/webpack.prod.conf.js:webpack 生产模式下的配置
'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')
// 用于在webpack中拷贝文件和文件夹
const CopyWebpackPlugin = require('copy-webpack-plugin')
// 用于基于模版生成html文件的
const HtmlWebpackPlugin = require('html-webpack-plugin')
// 将入口中所有的chunk,移到独立的分离的css文件中
const ExtractTextPlugin = require('extract-text-webpack-plugin')
// 用于压缩css模块
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
// 压缩js文件
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
// 生产模式配置
const env = require('../config/prod.env')
// 合并公共配置和生产环境独有的配置并返回一个用于生产环境的webpack配置文件
const webpackConfig = merge(baseWebpackConfig, {
// 用于生产环境的一些loader配置
module: {
rules: utils.styleLoaders({
// 在生产环境中使用extract选项,这样就会把thunk中的css代码抽离到一份独立的css文件中去
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
output: {
path: config.build.assetsRoot,
// build之后的文件的名称
// 这里[name]和[chunkhash]都是占位符
// 其中[name]指的就是模块的名称
// [chunkhash]chunk内容的hash字符串,长度为20
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
// 压缩javascript的插件
new UglifyJsPlugin({
// 压缩js的时候的一些基本配置
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
// 使用多进程并行运行和文件缓存来提高构建速度
parallel: true
}),
// 提取css文件到一个独立的文件中去
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'),
// 从所有额外的 chunk(additional chunk) 提取css内容
// (默认情况下,它仅从初始chunk(initial chunk) 中提取)
// 当使用 CommonsChunkPlugin 并且在公共 chunk 中有提取的 chunk(来自ExtractTextPlugin.extract)时
// 这个选项需要设置为true
// increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
allChunks: true,
}),
// 使用这个插件压缩css,主要是因为,对于不同组件中相同的css可以剔除一部分
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true, map: { inline: false } }
: { safe: true }
}),
// see https://github.com/ampedandwired/html-webpack-plugin
// / 创建一个html文件
new HtmlWebpackPlugin({
filename: config.build.index,
// 使用的模板的名称
template: 'index.html',
// 把script和link标签放在body底部
inject: true,
// 配置html的压缩行为
minify: {
// 移除注释
removeComments: true,
// 去除空格和换行
collapseWhitespace: true,
// 尽可能移除属性中的引号和空属性
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
// 根据模块的相对路径生成一个四位数的hash作为模块id
new webpack.HashedModuleIdsPlugin(),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks (module) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
//将webpack运行时和模块清单提取到其自己的文件中,以便
//防止在应用程序包更新时更新供应商哈希
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
//此实例从代码分割的块中提取共享块并将其捆绑
// see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
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
})
)
}
// 如果需要生成一分bundle报告,则需要使用下面的这个插件
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
build/build.js:node build/build.js执行的打包配置
'use strict'
// 检测node和npm版本,删除dist包,webpack构建打包,在终端输出构建信息并结束,如果报错,则输出报错信息。
// 检查npm和node的版本
require('./check-versions')()
// 设置环境变量NODE_ENV的值是production
process.env.NODE_ENV = 'production'
// node.js版本的rm -rf
const ora = require('ora')
// node.js版本的rm -rf
const rm = require('rimraf')
const path = require('path')
// 引入显示终端颜色模块
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
// 引入webpack在production环境下的配置文件
const webpackConfig = require('./webpack.prod.conf')
const spinner = ora('building for production...')
spinner.start()
// 删除打包目标目录下的文件
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
// 进行打包
webpack(webpackConfig, (err, stats) => {
spinner.stop()
if (err) throw err
// 输出打包的状态
process.stdout.write(stats.toString({
colors: true,
modules: false,
//如果您使用的是ts loader,那么将其设置为true将使TypeScript错误在构建期间显示出来。
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
// 如果打包出现错误
if (stats.hasErrors()) {
process.exit(1)
}
// 打包完成
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'
))
})
})
build/check-versions.js:对node和npm的版本判断
'use strict'
// 在终端为不同字体显示不同的风格
const chalk = require('chalk')
// 解析npm包的version
const semver = require('semver')
// 引入package.json文件
const packageConfig = require('../package.json')
// node版本的uninx shell命令
const shell = require('shelljs')
function exec (cmd) {
return require('child_process').execSync(cmd).toString().trim()
}
const versionRequirements = [
{
name: 'node',
// node的版本
// process.version就是node的版本
// semver.clean('v8.8.0') => 8.8.0
currentVersion: semver.clean(process.version),
// package.json中定义的node版本的范围
versionRequirement: packageConfig.engines.node
}
]
if (shell.which('npm')) {
// 如果npm命令存在的话
versionRequirements.push({
name: 'npm',
// 检查npm的版本 => 5.4.2
currentVersion: exec('npm --version'),
// package.json中定义的npm版本
versionRequirement: packageConfig.engines.npm
})
}
module.exports = function () {
const warnings = []
for (let i = 0; i < versionRequirements.length; i++) {
const mod = versionRequirements[i]
// semver.satisfies()进行版本之间的比较
if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
// 如果现有的npm或者node的版本比定义的版本低,则生成一段警告
warnings.push(mod.name + ': ' +
chalk.red(mod.currentVersion) + ' should be ' +
chalk.green(mod.versionRequirement)
)
}
}
// 要使用此模板,必须更新以下模块:
if (warnings.length) {
console.log(chalk.yellow('要使用此模板,必须更新以下模块:'))
for (let i = 0; i < warnings.length; i++) {
const warning = warnings[i]
}
// 退出程序
process.exit(1)
}
}
package.json:npm命令行
{
"name": "admin",
"version": "1.0.0",
"description": "A Vue.js project",
"private": true,
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "npm run dev",
"lint": "eslint --ext .js,.vue src",
"build": "node build/build.js"
},
"dependencies": {//生产开发需要的插件
"element-ui": "^2.15.1",
"node-sass": "^4.14.1",
"vue": "^2.5.2",
"vue-router": "^3.0.1"
},
"devDependencies": {//本地开发需要的插件
},
"engines": {
"node": ">= 6.0.0",
"npm": ">= 3.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}