详解从零搭建 vue2 vue-router2 webpack3 工程(7)
为什么要将vue-loader的options提取出来?其主要是用来配置CSS及CSS预处理语言的loader,开发环境可以不用配置,但是生产环境需要提取CSS、增加postcss-loader等,因此需要提取出来针对不同环境返回相应的options。后面会列出utils.vueLoaderOptions的内容。
为什么没有配置CSS的loader?理由和上面的vue-loader一样。
为什么没有配置path和publicPath?一方面是个性化参数,另外开发和生产可能不相同,因此在webpack.dev.config和webpack.prod.config中分别配置更为合适。
webpack.dev.config.js 内容如下:
var webpack = require('webpack');
var merge = require('webpack-merge');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var baseWebpackConfig = require('./webpack.base.config');
var utils = require('./utils');
var config = require('./config');
Object.keys(baseWebpackConfig.entry).forEach(function(name) {
baseWebpackConfig.entry[name] = [
`webpack-dev-server/client?http://localhost:${config.dev.port}/`,
"webpack/hot/dev-server"
].concat(baseWebpackConfig.entry[name])
});
module.exports = merge(baseWebpackConfig, {
output: {
path: config.dev.outputPath,
publicPath: config.dev.outputPublicPath
},
module: {
rules: utils.styleLoaders()
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
})
]
})
添加了HtmlWebpackPlugin后,index.html中就不需要在自己去引用打包的JS了,会自动根据打包的JS添加引用,这样更加方便,关于HtmlWebpackPlugin的配置,需要说明两点:
1.template的路径是相对于webpack编译时的上下文目录,说白了就是项目根目录,因此上面可以直接配置index.html,其指向的就是根目录下的index.html;
2.filename则是相对于webpack配置项output.path(打包资源存储路径)。
html-webpack-plugin关于template和filename路径源码如下:
// https://github.com/jantimon/html-webpack-plugin/blob/master/index.js // template this.options.template = this.getFullTemplatePath(this.options.template, compiler.context); // filename this.options.filename = path.relative(compiler.options.output.path, filename);
config.js内容如下:
module.exports = {
dev: {
outputPath: path.resolve(__dirname, '../static'),
outputPublicPath: '/',
port: 8000
},
prod: {
outputPath: path.resolve(__dirname, '../static'),
outputPublicPath: '/static/'
}
}
utils.js内容如下:
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var isProd = process.env.NODE_ENV === "production";
// 根据项目需求添加CSS预处理语言并安装相应的loader,以stylus-loader为例
var cssLang = [{
name: 'css',
reg: /\.css$/,
loader: 'css-loader'
}, {
name: 'stylus',
reg: /\.styl$/,
loader: "stylus-loader"
}];
function genLoaders(lang) {
var loaders = ['css-loader', 'postcss-loader'];
if (lang.name !== 'css') {
loaders.push(lang.loader);
}
if (isProd) {
// 生产环境需要提取CSS
loaders = ExtractTextPlugin.extract({
use: loaders
});
} else {
// 开发环境需要vue-style-loader将CSS提取到页面头部
loaders.unshift('vue-style-loader');
}
return loaders;
}
// 各种CSS的loader
exports.styleLoaders = function() {
var output = [];
cssLang.forEach(lang => {
output.push({
test: lang.reg,
use: genLoaders(lang)
})
})
return output;
};
// vue-loader的options
exports.vueLoaderOptions = function() {
var options = {
loaders: {}
};
cssLang.forEach(lang => {
options.loaders[lang.name] = genLoaders(lang);
});
return options;
}
内容版权声明:除非注明,否则皆为本站原创文章。
