Webpack - 在Build上打包外部JSON

时间:2018-05-04 20:47:07

标签: webpack

目前我有一个JSON文件,我在本地存储并导入为​​:

import TEAM_LIST from '../sample_info/teams';

然而,这个JSON变得陈旧。我正在尝试从存储JSON的URL导入数据:

https://example.com/teams.json

此网址很慢,此javascript旨在用于客户端目的。因此,我不希望每次加载我的应用程序时动态执行此操作。相反,每次我通过webpack构建应用程序时,我只想从URL中获取此JSON并在构建中本地打包它。

如何调整我的webpack文件呢?这是我目前的配置:

/* eslint-disable */
var webpack = require('webpack');
var path = require('path');
var BundleTracker = require('webpack-bundle-tracker');

module.exports = {

  entry: {
    user: ['./client/index.js'],
  },

  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].bundle.js',
    publicPath: "/static_/",
  },

  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.css$/,
        loaders: ["style-loader", "css-loader"]
      },
      {
        test: /\.(png|jpg|otf|woff2)$/,
        loader: 'url-loader'
      }

    ]
  },

  resolve: {
    extensions: ['.js', '.jsx']
  },

  plugins: [
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new BundleTracker({filename: './webpack-stats.json'})
  ]

}

1 个答案:

答案 0 :(得分:1)

这是我最终解决的问题。

  plugins: [
    new webpack.WatchIgnorePlugin([
      path.resolve(__dirname, './client/precached_data/'),
    ]),
    new WebpackPreBuildPlugin(function(stats) {
      // Do whatever you want before build starts...
      var file = fs.createWriteStream("sample_info/teams");
      var response = request('GET', "https://example.com/teams.json");
      file.write(response.body.toString('utf-8'));

    }),
  ]