简体   繁体   English

包含package.json文件失败时使用webpack

[英]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. 我正在尝试使用WebPack从使用commonJS模块的基于同构的JS代码创建浏览器包。 To expose the version in the package.json I do the following in my index.js: 要在package.json中公开版本,我在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: 但是,默认情况下,WebPack会将package.json文件视为JavaScript,这会导致解析器错误,因为它实际上是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 . 我已经读过,对于JSON文件,需要json-loader插件,模块路径必须调整为json!../package.json While this actually works for WebPack, it will break the code when running it in node.js natively. 虽然这实际上适用于WebPack,但它会在本地运行node.js时破坏代码。

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? 那么,引用package.json (或任何其他JSON文件)的正确方法是什么,以便WebPack可以创建浏览器包而不是用任何仅支持WebPack的模块路径来污染代码?

Try use as usual: 尝试照常使用:

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

But in webpack.config.json : 但是在webpack.config.json

...
module: {
    loaders: [{
        test: /\.json$/,
        loader: 'json'
    }, ...]
}
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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