感谢Sean Larkin从Webpack项目中接触到我并帮助我弄清楚如何完成这件事。我需要创建一个自定义加载器来处理读取现有manifest.json
并添加我感兴趣的领域。
// File: src/manifest-loader.js
const fs = require('fs');
// A loader to transform a partial manifest.json file into a complete
// manifest.json file by adding entries from an NPM package.json.
module.exports = function(source) {
const pkg = JSON.parse(fs.readFileSync('./package.json'));
const merged = Object.assign({}, JSON.parse(source), {
'name': pkg.name,
'description': pkg.description,
'version': pkg.version,
'author': pkg.author,
'homepage_url': pkg.homepage,
});
const mergedJson = JSON.stringify(merged);
// In Webpack, loaders ultimately produce JavaScript. In order to produce
// another file type (like JSON), it needs to be emitted separately.
this.emitFile('manifest.json', mergedJson);
// Return the processed JSON to be used by the next item in the loader chain.
return mergedJson;
};
然后配置webpack使用我的自定义manifest-loader
。
// File: webpack.config.js
const path = require('path');
module.exports = {
// Tell Webpack where to find our custom loader (in the "src" directory).
resolveLoader: {
modules: [path.resolve(__dirname, "src"), "node_modules"]
},
// The path to the incomplete manifest.json file.
entry: "./manifest.json",
output: {
// Where the newly built manifest.json will go.
path: path.resolve(__dirname, 'dist'),
// This file probably won't actually be used by anything.
filename: "manifest.js",
},
module: {
rules: [
{
// Only apply these loaders to manifest.json.
test: /manifest.json$/,
// Loaders are applied in reverse order.
use: [
// Second: JSON -> JS
"json-loader",
// First: partial manifest.json -> complete manifest.json
"manifest-loader",
]
}
]
}
};
结果,运行的WebPack时,是包含manifest.js
和manifest.json
,包含一切manifest.json
从原来的顶层manifest.json
加上package.json
附加信息一dist/
目录。额外的manifest.js
是一个脚本,它将manifest.json
的内容暴露给项目中需要它的任何其他JavaScript。这可能不太有用,但Chrome扩展可能想要在某个脚本中以require
这样的方式以友好的方式公开某些信息。
它的固定?或者如果你想要http://webpack.github.io/docs/usage-with-gulp.html,那么你可以尝试使用gpack,所以你可以使用这个软件包'gulp-json-editor'。 –
@RahmatAligos谢谢,但我的目标是简化构建过程,以便我不必同时使用Gulp和Webpack。这是阻止我切换的少数几个问题之一,这里的定制加载器解决方案解决了我的问题。 – user108471
这是一个很棒的解决方案!我用文件加载器而不是json-loader,所以我没有得到manifest.js并做了一些其他的调整:https://gist.github.com/bronson/163d7d4dde2a845ea3d6af3a0d86d174非常感谢你回答你自己的问题。 – bronson