简体   繁体   中英

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. So far, any method I try results in reading the plugins 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:

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. But you can try this approach out, here webpack context is used:

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:

// 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:

plugins: [
    new HelloWorldPlugin({
        packageJsonFile: path.resolve(__dirname, './package.json'),
    })
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM