如何使用webpack构建JSON文件?

时间:2017-05-28 21:52:58

标签: javascript npm webpack

我想以“更智能”的程序化方式汇编Chrome扩展程序使用的manifest.json文件。我使用npm进行依赖项解析,package.json包含manifest.json文件的一些共享字段,包括“name”,“description”和“version”。

有没有办法定义类似于部分manifest.json文件的内容,其中包含所有特定于Chrome的内容,但是在适当的时候填写共享值?我发现这在Gulp中非常简单:

var gulp = require('gulp');
var fs = require('fs');
var jeditor = require('gulp-json-editor');

gulp.task('manifest', function() {
    var pkg = JSON.parse(fs.readFileSync('./package.json'));
    gulp.src('./manifest.json')
      .pipe(jeditor({
        'name': pkg.name,
        'description': pkg.description,
        'version': pkg.version,
        'author': pkg.author,
        'homepage_url': pkg.homepage,
      }))
      .pipe(gulp.dest("./dist"));
});

即使有一些为此目的而设计的npm包,有人可以向我解释一般这样的事情是怎么做的吗?我知道Webpack 2有一个内置的json加载器,但我不清楚如何在这样的情况下使用它。

7 个答案:

答案 0 :(得分:5)

来自Webpack项目的Sean Larkin向我伸出援手,帮助我弄清楚如何完成这项工作。我需要创建一个自定义加载器来处理读取现有的manifest.json并添加我感兴趣的字段。

// File: src/manifest-loader.js

const fs = require('fs');

// A loader to transform a partial manifest.json file into a complete
// manifest.json file by adding entries from an NPM package.json.
module.exports = function(source) {
  const pkg = JSON.parse(fs.readFileSync('./package.json'));
  const merged = Object.assign({}, JSON.parse(source), {
    'name': pkg.name,
    'description': pkg.description,
    'version': pkg.version,
    'author': pkg.author,
    'homepage_url': pkg.homepage,
  });
  const mergedJson = JSON.stringify(merged);
  // In Webpack, loaders ultimately produce JavaScript. In order to produce
  // another file type (like JSON), it needs to be emitted separately.
  this.emitFile('manifest.json', mergedJson);
  // Return the processed JSON to be used by the next item in the loader chain.
  return mergedJson;
};

然后配置webpack以使用我的自定义manifest-loader

// File: webpack.config.js

const path = require('path');

module.exports = {
  // Tell Webpack where to find our custom loader (in the "src" directory).
  resolveLoader: {
    modules: [path.resolve(__dirname, "src"), "node_modules"]
  },

  // The path to the incomplete manifest.json file.
  entry: "./manifest.json",
  output: {
    // Where the newly built manifest.json will go.
    path: path.resolve(__dirname, 'dist'),
    // This file probably won't actually be used by anything.
    filename: "manifest.js",
  },

  module: {
    rules: [
      {
        // Only apply these loaders to manifest.json.
        test: /manifest.json$/,
        // Loaders are applied in reverse order.
        use: [
          // Second: JSON -> JS
          "json-loader",
          // First: partial manifest.json -> complete manifest.json
          "manifest-loader",
        ]
      }
    ]
  }
};

运行Webpack时,结果是dist/目录,其中包含manifest.jsmanifest.json,其中manifest.json包含原始顶层manifest.json中的所有内容加上package.json的其他信息。额外的manifest.js是一个脚本,它将manifest.json的内容公开给项目中需要它的任何其他JavaScript。这可能不是太有用,但Chrome扩展程序可能会想到require在某个脚本中以友好的方式公开这些信息。

答案 1 :(得分:3)

实际上有一个比@ user108471的解决方案更优雅的解决方案(尽管它受其启发),那就是使用copy-webpack-plugin。借助其transform功能,您可以在将其复制到目标位置之前将所需的值动态添加到manifest.json

它有两个优点:

  • 它不会生成多余的manifest.js捆绑包(@bronson's solution也可以解决此问题)
  • 您无需在其他require文件中manifest.json .js(对我而言似乎是倒退的)

最小设置可能是这样:

webpack.config.js

// you can just require .json, saves the 'fs'-hassle
let package = require('./package.json');

function modify(buffer) {
   // copy-webpack-plugin passes a buffer
   var manifest = JSON.parse(buffer.toString());

   // make any modifications you like, such as
   manifest.version = package.version;

   // pretty print to JSON with two spaces
   manifest_JSON = JSON.stringify(manifest, null, 2);
   return manifest_JSON;
}


module.exports = {

   // ...

   plugins: [
      new CopyWebpackPlugin([
         {
            from: "./src/manifest.json",
            to:   "./dist/manifest.json",
            transform (content, path) {
                return modify(content)
            }
         }])
   ]

}

答案 2 :(得分:2)

const manifest = {
  entry: './src/chrome_extension/dummy_index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'DELETED.js',
  },
  plugins: [
    new CleanWebpackPlugin(),
    new CopyWebpackPlugin({
      patterns: [
        {from: 'LICENSE.md'},
        {from: 'assets/img/icon.png', to: `${ASSETS_PATH}/icon.png`},
        {from: 'src/chrome_extension/manifest.json',
          transform: function(manifestBuffer, path) {
            const manifestString = manifestBuffer.toString()
                .replace(/\$\{OPTIONS_PAGE_PATH\}/g, OPTIONS_PAGE_PATH)
                .replace(/\$\{CONTENT_SCRIPT_PATH\}/g, CONTENT_SCRIPT_PATH)
                .replace(/\$\{ASSETS_PATH\}/g, ASSETS_PATH);
            return Buffer.from(manifestString);
          },
        },
      ],
    }),
    new RemoveFilesWebpackPlugin({
      after: {
        log: false,
        include: [
          'dist/DELETED.js',
        ],
      },
    }),
  ],
  stats: 'none',
  mode: 'none',
};

答案 3 :(得分:0)

我正在使用你的脚本,我在NPM上发布了一些有点修改过的版本:https://github.com/bronson/manifest-package-loader

希望它像java.lang.NoClassDefFoundError一样简单并更新您的webpack.config.js。

巧合的是,就在今天早上,我遇到了化学装载机,它可能也有效:https://github.com/mrmisterman/chem-loader

答案 4 :(得分:0)

我在以下Webpack 4中的解决方案。这是使用Webpack加载程序生成json文件的通用解决方案,但它也适用于manifest.json文件。

webpack.config.js

const ExtractTextPlugin = require("extract-text-webpack-plugin");
const resolve = require("path").resolve;

module.exports = {
    entry: {
        entry: resolve(__dirname, "app/main.js"),
    },
    module: {
        rules: [
            {
                test: /manifest\.js$/,
                use: ExtractTextPlugin.extract({
                    use: []  // Empty array on purpose.
                })
            }
        ],
        {
            test: /\.png$/,
            use: [{
                loader: "file-loader",
                options: {
                    context: resolve(__dirname, "app"),
                    name: "[path][name].[ext]",
                    publicPath: "/",
                }
            }]
        }
    },
    output: {
        filename: "[name].js",
        path: resolve(__dirname, 'dist'),
    },
    plugins: [
        new webpack.EnvironmentPlugin(["npm_package_version"]),  // automagically populated by webpack, available as process.env.npm_package_version in loaded files.
        new ExtractTextPlugin("manifest.json"),
    ]
};

app / main.js

const manifest = require('./manifest.js');

// Other parts of app …

app / manifest.js

const icon = require('./icon.png');  

const manifestData = {  
    icon: {"128": icon},  // icon.png will be in the emitted files, yay!
    version: process.env.npm_package_version,  // See webpack.config.js plugins
    // other manifest data …
};

// Whatever string you output here will be emitted as manifest.json:
module.exports = JSON.stringify(manifestData, null, 2);

package.json依赖项

{
    "extract-text-webpack-plugin": "4.0.0-beta.0",
    "file-loader": "1.1.11",
    "webpack": "4.12.0",
}

答案 5 :(得分:0)

如果您使用的是webpack 4,它非常简单。我们不需要指定任何显式的json加载器

注意:我只是将所有内容都捆绑到一个html文件中,但是您会发现webpack.config.js文件中没有json加载器

webpack.config.js

const HtmlWebPackPlugin = require("html-webpack-plugin");
 const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin');

module.exports = {
 module: {
rules: [
  {
    test: /\.js$/,
    exclude: [/node_modules/],
    use: [{
      loader: 'babel-loader'
    }],
  },
  {
    test: /\.css$/,
    use: ["style-loader", "css-loader"]
  },
  {
      test: /\.ico$/,
      use: ["file-loader"]
  },
  {
    test: /\.html$/,
    use: [
      {
        loader: "html-loader",
        options: { minimize: true }
      }
    ]
  }
],
},
 plugins: [
new HtmlWebPackPlugin({
  template: "./src/index.html",
  filename: "./index.html",
  inlineSource: '.(js|css)$'
}),
new HtmlWebpackInlineSourcePlugin(),
],
devServer: {
  compress: true,
  disableHostCheck: true,
  }
}

在我的app.js中,我只使用

import data from './data/data.json'

答案 6 :(得分:-1)

尝试这个包,你可以读取你的json文件,然后在用它自定义之后构建新的json。 https://github.com/webpack-contrib/json-loader