开场
当我们使用vue-cli创建项目的时候,build文件夹的配置文件里面除了拥有编译相关的dev文件和打包相关的prod文件以外,还有另外一个使用很频繁的base文件。这个base里使用了一些编译和打包时候都会用到的信息,所以被单独提取出来。因此我们在学习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 = {
// 基础上下文
context: path.resolve(__dirname, '../'),
// webpack的入口文件,
// 打包时,生成entry chunk。如果entry是字符串或者数组,则只会生成一个chunk。如果是对象,则会生成多个chunk。
entry: {
app: './src/main.js'
},
/**
* The top-level output key contains set of options instructing webpack on how and where it should output your bundles,
* assets and anything else you bundle or load with webpack.
*
* */
output: {
path: config.build.assetsRoot,
/**
* when creating multiple bundles via more than one entry point, code splitting, or various plugins,
* you should use one of the following substitutions to give each bundle a unique name
*
* */
// 输出文件的名字,与prod整合时,会被替换成prod里的命名风格
filename: '[name].js',
// 根据环境变量选择路径
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
/**
* 当webpack试图去加载模块的时候,它默认是查找以 .js 结尾的文件的,
* 它并不知道 .vue 结尾的文件是什么鬼玩意儿,
* 所以我们要在配置文件中告诉webpack,
* 遇到 .vue 结尾的也要去加载,
* 添加 resolve 配置项,如下:
*/
resolve: {
extensions: ['.js', '.vue', '.json'],
// 设置别名
alias: {
// 简化导入代码
'vue$': 'vue/dist/vue.esm.js',
// 一件回到src文件夹,不用一直回到上一级
'@': resolve('src'),
}
},
module: {
rules: [
{
// vue-loader vue文件转js文件
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
// babel-loader ES6转ES5, JSX转JS
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]')
}
}
]
},
// 不知道干嘛的 估计用处不大
node: {
// prevent webpack from injecting useless setImmediate polyfill because Vue
// source contains it (although only uses it if it's native).
setImmediate: false,
// prevent webpack from injecting mocks to Node native modules
// that does not make sense for the client
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}