假定我们的项目目录为如下的样子:
- root/
- assets/
- app/
- global.js
- index/
- index.js
- auth/
- login.js
- register.js
- ...
- webpack.config.js
- public/
- assets/
- build/
使用如下的 webpack 配置:
var webpack = require('webpack');
var fs = require('fs');
var path = require('path');
var glob = require('glob');
const debug = process.env.NODE_ENV !== 'production';
function entries (globPath) {
var files = glob.sync(globPath);
var entries = {}, entry, dirname, basename;
for (var i = 0; i < files.length; i++) {
entry = files[i];
dirname = path.dirname(entry);
basename = path.basename(entry, '.js');
entries[path.join(dirname, basename)] = './' + entry;
}
return entries;
}
module.exports = {
entry: entries('app/**/*.js'),
output: {
path: path.join(__dirname, '..', 'public', 'assets', 'build'),
publicPath: '/assets/build/',
filename: '[name]' + (debug ? '' : '-[chunkhash]') + '.js',
chunkFilename: '[id]' + (debug ? '' : '-[chunkhash]') + '.js'
},
plugins: [
function () {
this.plugin('done', function (stats) {
stats = stats.compilation.getStats().toJson({
hash: true,
publicPath: true,
assets: true,
chunks: false,
modules: false,
source: false,
errorDetails: false,
timings: false
});
var json = {}, chunk;
for (var key in stats.assetsByChunkName) {
if (stats.assetsByChunkName.hasOwnProperty(key)) {
chunk = stats.assetsByChunkName[key];
json[key + '.js'] = chunk[0];
}
}
fs.writeFileSync(
path.join(__dirname, '..', 'public', 'assets', 'build', 'rev-manifest.json'),
JSON.stringify(json, null, 2)
);
});
}
]
};
这样,我们就可以得到形如这样的构建输出:
- root/
- assets/
- ...
- public/
- assets/
- build/
- rev-manifest.json
- app/
- global.js
- auth/
- login.js
- register.js
- ...
意义何在???
关键在于 rev-manifest.json
文件,我们查看一下文件内容:
{
"app/global.js": "app/global.js",
"app/index/index.js": "app/index/index.js",
"app/auth/login.js": "app/auth/login.js",
"app/auth/register.js": "app/auth/register.js",
}
意义何在???
好吧,我们再看一下在生产环境下的构建输出:
{
"app/global.js": "app/global-6ff91e44b26765ae797a.js",
"app/index/index.js": "app/index/index-d294c62e36a91fa7237d.js",
"app/auth/login.js": "app/auth/login-f04b1d5a3cffac4d70aa.js",
"app/auth/register.js": "app/auth/register-502d794e8e0c7f1a230d.js",
}
如果配合模板中的函数:
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="{{ assets_url('app/index/index.js') }}"></script>
</head>
<body>
</body>
</html>
assets_url
函数可以直接获取 rev-manifest.json
内容,根据给定的 key
得到对应的构建文件的可访问路径,自动的根据不同的环境获取到正确的引用结果。
同时,我们可以在源代码目录里面,根据需求对代码进行模块化管理,构建出来的代码结构会和我们源代码中管理的一致。
这样一来,既可以享受构建系统的优势,又无需在新增或修改模块时改动 webpack.config.js
,是不是很方便呢?