感謝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