解析
webpack.base.conf.js
配有一些基础要素包括,会和 通常的webapck.config.js类似。
// 0. 引入一些依赖
var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: { // 1. 入口文件配置
app: './src/main.js'
},
output: { // 2. 输出文件配置
path: config.build.assetsRoot, // 输出目录的绝对路径
filename: '[name].js', // 输出的文件的名称,name为对应entry的key
publicPath: process.env.NODE_ENV === 'production' // 生产模式或开发模式下html、js等文件内部引用的公共路径(请求的静态资源绝对路径)
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: { // 3. 文件解析配置,设置模块如何被解析
// 在代码中通过require/import模块的相关配置,预定义了.js 和.vue的扩展,这样在引用一个hello.js文件时,我们只需要import Hello from '/path/to/directory/hello'就能够做到
extensions: ['.js', '.vue', '.json'], // 自动解析确定的拓展名,使导入模块时不带拓展名,即在require/import模块路径中自动补全文件后缀
alias: { // 路径的别名,require/import模块路径中可以通过别名缩短路径字符串的长度,节省了大量时间去计算文件与文件之间的嵌套关系
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
}
},
module: { // 4. 模块解析配置,如何处理项目不同类型的模块
rules: [
{
test: /\.(js|vue)$/, // 代码文件后缀
loader: 'eslint-loader',
enforce: "pre",
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
},
{
test: /\.vue$/, // vue文件后缀
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/, // js文件后缀
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, // 图片文件后缀
loader: 'url-loader',
query: {
limit: 10000, // 当图片大小小于10kb时,会生成一个base64串打包到编译后的js文件里,若超过10kb会单独生成一个文件
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, // 字体文件后缀
loader: 'url-loader',
query: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
}
}
webpack.dev.conf.js
这个配置将针对我们本机开发时使用。
var utils = require('./utils') // 工具方法
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge') // 合并配置文件
var baseWebpackConfig = require('./webpack.base.conf') // 开发时和运行时共享的的webpack配置文件
var HtmlWebpackPlugin = require('html-webpack-plugin') // 操作html文件的插件
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
Object.keys(baseWebpackConfig.entry).forEach(function (name) { // 启用热加载
baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})
module.exports = merge(baseWebpackConfig, {
module: { //通过传入一些配置来获取rules配置,此处传入了sourceMap: false,表示不生成sourceMap
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
},
devtool: '#cheap-module-eval-source-map', // 指定sourceMap类型 方便源码定位
plugins: [ // 一些额外的插件,不是必须的
new webpack.DefinePlugin({ // 编译时配置的全局变量
'process.env': config.dev.env //当前环境为开发环境
}),
new webpack.HotModuleReplacementPlugin(), // 热更新插件
new webpack.NoEmitOnErrorsPlugin(), // 不触发错误,即编译后运行的包正常运行,编译出错时跳过那部分代码
new HtmlWebpackPlugin({ // 以现有html为模板去生成新的html以及相应配置,比如编译后文件的引入
filename: 'index.html', //生成的文件名
template: 'index.html', //模板
inject: true // 表示css、js路径自动添加到该html文件里(css->header标签,js->body),也可配置
}),
new FriendlyErrorsPlugin() // 友好的错误提示
]
})
webpack.prod.conf.js
生产环境下的webpack配置,通过merge方法合并webpack.base.conf.js基础配置,这个文件将定义打包好的生成文件。
var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin') // 针对 vue文件里的样式单独拆分,这样他们会被合并到css文件里去
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
var env = config.build.env
var webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true
})
},
devtool: config.build.productionSourceMap ? '#source-map' : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
new webpack.DefinePlugin({
'process.env': env
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
sourceMap: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css')
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: {
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',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
},
chunksSortMode: 'dependency'
}),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module, count) {
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
chunks: ['vendor']
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
if (config.build.productionGzip) {
var 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) {
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
参考
Vue 入门系列之手把手教你搭Webpack
vue-cli中的webpack配置
Vue.js学习系列四——Webpack打包工具的使用(装修中……)