FluffySamurai
FluffySamurai

Reputation: 588

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?

Upvotes: 2

Views: 883

Answers (2)

vilu
vilu

Reputation: 51

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

Upvotes: 2

asvetly
asvetly

Reputation: 1846

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'),
    })
]

Upvotes: 1

Related Questions