keithhackbarth
keithhackbarth

Reputation: 10146

Webpack - Package External JSON on Build

Currently I have a JSON file that I store locally and import as:

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

However this JSON gets stale. I'm trying instead to import the data from a URL that the JSON is stored on:

https://example.com/teams.json

This URL is slow and this javascript is intended for client purposes. Therefore, I do NOT want to do this dynamically when my app is loaded each time. Instead, every time I build the app via webpack I just want to grab this JSON from the URL and package it locally in the build.

How do I adjust my webpack file to do so? Here is my current configuration:

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

}

Upvotes: 0

Views: 129

Answers (1)

keithhackbarth
keithhackbarth

Reputation: 10146

Here's how I ended up solving.

  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'));

    }),
  ]

Upvotes: 1

Related Questions