原文:https://www.cnblogs.com/xiaozhangzhang/p/9076375.html
参考:https://www.webpackjs.com/configuration/
说明
此仓库为vue-cli webpack的配置分析[v2.9.3]
分析仅包括build目录下webpack.dev.conf.js和webpack.base.conf.js。check-versions.js文件。check-versions.js是检测npm和node版本,与webpack无关。
webpack.dev.conf.js
'use strict'
const utils = require('./utils') //工具函数集合
const webpack = require('webpack')
const config = require('../config')//配置文件
const merge = require('webpack-merge')// webpack 配置合并插件通过webpack-merge实现webpack.dev.conf.js对wepack.base.config.js的继承
const path = require('path')// node的文件路径工具
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')// 自动生成 html 并且注入到 .html 文件中的插件
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')// webpack错误信息提示插件
const portfinder = require('portfinder')// 查看空闲端口位置,默认情况下搜索8000这个端口
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
// cheap-module-eval-source-map is faster for development.
//后面的一些配置都在/config/index.js中改,可以看webpack的配置说明;devtool: '#eval-source-map'可以方便进行debugger
devtool: config.dev.devtool,
// these devServer options should be customized in /config/index.js
devServer: {
clientLogLevel: 'warning',//对控制台DevTools的输出进行设置
//当使用 HTML5 History API 时,任意的 404 响应都可能需要被替代为 index.html
historyApiFallback: {
rewrites: [
{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
],
},
hot: true, //启用模块热加载
contentBase: false, // since we use CopyWebpackPlugin.告诉服务器从哪里提供内容。只有在你想要提供静态文件时才需要
compress: true, //一切服务都启用gzip 压缩
host: HOST || config.dev.host,//指定使用一个 host。默认是 localhost。
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,//将API请求发送到同域名下的服务器
quiet: true, // necessary for FriendlyErrorsPlugin,启用 quiet 后,除了初始启动信息之外的任何内容都不会被打印到控制台。这也意味着来自 webpack 的错误或警告在控制台不可见。若用FriendlyErrorsPlugin 此处为 true
watchOptions: {
poll: config.dev.poll,
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.// 显示文件的正确名字
new webpack.NoEmitOnErrorsPlugin(),
//当webpack编译错误的时候,来中端打包进程,防止错误代码打包到文件中
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 {
// publish the new Port, necessary for e2e tests
process.env.PORT = port
// add port to devServer config
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)
}
})
})
devServer的详细配置戳
webpack.base.conf.js下面那些配置项的概念见
webpack.base.conf.js是开发和生产共同使用提出来的基础配置文件,主要实现配制入口,配置输出环境,配置模块resolve和插件等。
//获得绝对路径
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
//path.join将路径片段进行拼接,而path.resolve将以/开始的路径片段作为根目录
module.exports = {
context: path.resolve(__dirname, '../'),
entry: {
app: './src/main.js'//配置入口,默认为单页面所以只有app一个入口
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],//自动的扩展后缀,比如一个js文件,则引用时书写可不要写.js
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
}
},
module: {
rules: [
//使用vue-loader将vue文件转化成js的模块
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
//js文件需要通过babel-loader进行编译成es5文件以及压缩等操作
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},
{
//图片、音像、字体都使用url-loader进行处理,超过10000会编译成base64
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: {
//以下选项是Node.js全局变量或模块,这里主要是防止webpack注入一些Node.js的东西到vue中
setImmediate: false,
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}