Webpack是一款模块加载及打包部署工具。它有以下优点:
为什么我要选用webpack呢?
除了它上面的优点外,还有就是我将它与之前我使用的requirejs比较了下,webpack自动将js,css,img,html等资源组合在一个模块中,比之前我们手动用文件名的形式来关联更方便、更优雅,这样很舒服地实现模块化和组件化的目标。
下面是我在本站所使用的webpack配置文件(webpack.config.js),里面有一些简单的注释,之后我会对其中一些作具体的记录。
var path = require('path');
var node_modules = path.resolve(__dirname, 'node_modules');
// 提取文件的webpack插件
var ExtractTextPlugin = require("extract-text-webpack-plugin");
// 全局依赖
var deps = [
'jquery/dist/jquery.js'
];
var config = {
// 配置输入模块
entry: {
'index': './js/index.js',
'article': './js/article.js',
'tag': './js/tag.js'
},
// 配置加载的默认搜索的路径
resolve: {
extensions: ["", ".js"],
modulesDirectories: [
path.resolve(__dirname, 'node_modules'),
path.resolve(__dirname, 'css'),
path.resolve(__dirname, 'js')
],
alias: {}
},
// 配置输出
output: {
filename: "js/[name].js?[hash]-[hash]",
chunkFilename: "[name].js?[hash]-[hash]",
path: __dirname + "/assets/",
publicPath: "/assets/"
},
module: {
noParse: [],
loaders: [
// 因为less现存在数学运算的问题(如calc无法计算),所以将其与css分离
{ test: /\.less$/,
loader: ExtractTextPlugin.extract(
"style-loader",
"css-loader!less-loader?sourceMap",
{
// 图片、字体资源打包到css上级目录
publicPath: "../"
}
)
},
{ test: /\.css$/,
loader: ExtractTextPlugin.extract(
"style-loader",
"css-loader?sourceMap",
{
// 图片、字体资源打包到css上级目录
publicPath: "../"
}
)
},
// babel处理es6
{
test: /\.js?$/,
exclude: [
node_modules
],
loader: 'babel'
},
// 导出全局依赖
{
test: path.resolve(node_modules, deps[0]),
loader: 'expose?jQuery'
},
// 图片及字体打包
{
test: /\.(ttf|eot|svg|png|gif|woff(2)?)(\?.*?)?$/,
loader: "file-loader"
}
]
},
plugins: [
// 配置以文件形式打包css
new ExtractTextPlugin("css/[name].css?[hash]-[chunkhash]-[contenthash]-[name]", {
disable: false,
allChunks: true
})
]
};
// 其它
deps.forEach(function (dep) {
var depPath = path.resolve(node_modules, dep);
// 设置替换模块名称与路径
config.resolve.alias[dep.split(path.sep)[0].split('\/')[0]] = depPath;
// 设置不解析的文件
config.module.noParse.push(depPath);
});
module.exports = config;
感谢您的阅读!
如果看完后有任何疑问,欢迎拍砖。
欢迎转载,转载请注明出处:http://www.yangrunwei.com/a/1.html
邮箱:glowrypauky@gmail.com
QQ: 892413924