[英]How to read package.json from webpack plugin
I'm currently working on a webpack plugin, and I am trying to find a way to read the package.json
of the repo calling my plugin.我目前正在开发一个 webpack 插件,我正在尝试找到一种方法来读取调用我的插件的 repo 的
package.json
。 So far, any method I try results in reading the plugins package.json
.到目前为止,我尝试的任何方法都会导致读取插件
package.json
。
Is there any way to access that file directly?有没有办法直接访问该文件?
Here's the late answer, but I hope this helps others.这是迟到的答案,但我希望这对其他人有帮助。 I was struggling with the same thing and ended up reading the path from
process.env.npm_package_json
and created variables this way:我在同样的事情上苦苦挣扎,最终从
process.env.npm_package_json
读取路径并以这种方式创建变量:
let packageJson = JSON.parse(require('fs').readFileSync(process.env.npm_package_json).toString());
let author = packageJson.author; // Your Name
let version = packageJson.version; // 1.0.0
You can't be sure about where consumer's package.json is.你不能确定消费者的 package.json 在哪里。 But you can try this approach out, here webpack context is used:
但是你可以尝试这种方法,这里使用了 webpack 上下文:
apply(compiler: Compiler) {
compiler.hooks.beforeRun.tap('HelloWorldPlugin', () => {
console.log(`Path where webpack was executed: ${ compiler.options.context }`);
console.log(require(`${ compiler.options.context }/package.json`));
})
}
Another two approaches that also assume that consumer's package.json is located in the same dir with webpack config:另外两种方法也假设消费者的 package.json 与 webpack 配置位于同一目录中:
// via **compiler.inputFileSystem**
apply(compiler: Compiler) {
compiler.hooks.beforeRun.tap('HelloWorldPlugin', () => {
console.log(compiler.inputFileSystem.readFileSync('./package.json').toString());
})
}
// via **process.cwd()**
apply(compiler: Compiler) {
compiler.hooks.beforeRun.tap('HelloWorldPlugin', () => {
console.log(require('path').resolve(process.cwd(), 'package.json'));
})
}
Or you can just pass it through params in consumer's webpack.config.js:或者你可以通过消费者的 webpack.config.js 中的参数传递它:
plugins: [
new HelloWorldPlugin({
packageJsonFile: path.resolve(__dirname, './package.json'),
})
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.