简体   繁体   中英

Use webpack when including the package.json file fails

I am trying to use WebPack to create a bundle for the browser from my isomorphic based JS code using commonJS modules. To expose the version in the package.json I do the following in my index.js:

var pjson = require("../package.json");
module.exports = {
    version: pjson.version
};

However, WebPack will treat the package.json file as JavaScript by default, which causes a parser error as it is actually JSON:

package.json Line 2: Unexpected token :

I've read that for JSON files, the json-loader plugin is required and the module path must be adjusted to json!../package.json . While this actually works for WebPack, it will break the code when running it in node.js natively.

So whats the correct way of referencing the package.json (or any other JSON file) so that WebPack can create a browser bundle AND not to taint the code with any WebPack-only module paths?

Try use as usual:

var pjson = require("../package.json");

But in webpack.config.json :

...
module: {
    loaders: [{
        test: /\.json$/,
        loader: '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