Banjer
Banjer

Reputation: 8320

Reading in webpack assets json with webpack-dev-server

Up until now, I've been building my isomorphic Node/Express/React app with webpack and serving up my bundle.js without a problem by including the following in my index html file:

<script src='/bundle.js'></script>

However, for deploying to production I've found I need a cache-busting mechanism in place, so I reached for the webpack-manifest-plugin so I can add the unique build hash to the bundle.js file.

The webpack config with the plugin looks like:

webpack.config.js

var ManifestPlugin = require('webpack-manifest-plugin');

var output = {
  path: path.join(__dirname, [ '/', config.get('buildDirectory') ].join('')),
  filename: "bundle.[hash].js"
};

which outputs a manifest.json file to the build directory that looks like:

{
  "main.js": "bundle.af0dc43f681171467c82.js"
}

I was thinking I could then read in manifest.json with something like:

var manifestPath = path.join(__dirname, [ '/', config.get('buildDirectory') ].join(''),'/manifest.json');
var manifest = require(manifestPath)

but I get

Error: Cannot find module 'C:\Users\banjer\projects\foo\build\manifest.json'

Is this because webpack-dev-server keeps the build directory in memory and not on disk (AFAIK)? Whats the best method to read in this manifest.json and inject the bundle filename into my main index html file, e.g.?:

<script src='/bundle.af0dc43f681171467c82.js'></script>

The docs on these various asset plugins don't explain this step at all, but then again I think its less obvious because of webpack-dev-server...or something in my stack that I don't quite grasp yet.

Upvotes: 3

Views: 3867

Answers (1)

Banjer
Banjer

Reputation: 8320

I went a simpler route and used version from package.json to append to bundle.js as a cache buster.

webpack.config.js

var output = {
  path: path.join(__dirname, [ '/', config.get('buildDirectory') ].join('')),
  filename: 'bundle.' + JSON.stringify(require('./package.json').version) + '.js'
};

module.exports = {
  output: output,
...
}

then I read in package.json in a similar manner from the entry script that generates my .ejs index file that has my script tags.

Upvotes: 0

Related Questions