Skip to content

Instantly share code, notes, and snippets.

@sterlingwes
Last active May 2, 2017 16:04
Show Gist options
  • Save sterlingwes/60e90bb56ce8ca65f160514a2dabf287 to your computer and use it in GitHub Desktop.
Save sterlingwes/60e90bb56ce8ca65f160514a2dabf287 to your computer and use it in GitHub Desktop.
webpack server side rendering with file loader (ie: require()'d images)
const fs = require('fs')
const utils = require('loader-utils')
const defaultOptions = {
extensions: ['.png', '.jpg'],
filePrefix: 'img/img-',
hashLength: 6
}
module.exports = function (options) {
options = extendDefaults(options)
const { extensions } = options
extensions.forEach(ext => {
require.extensions[ext] = requireFile.bind({ options }, ext)
})
}
function requireFile (ext, nodeModule) {
const { id } = nodeModule
const { filePrefix, hashLength } = this.options
const buffer = fs.readFileSync(id)
const hash = utils.getHashDigest(buffer).substr(0, hashLength)
const bundlePath = `${filePrefix}${hash}${ext}`
nodeModule.exports = bundlePath
}
function extendDefaults (options) {
return Object.assign({}, defaultOptions, options || {})
}

Usage

require('./loaderHook')() before any require statements with the non-js files you're looking to load.

Loader hook can take an options object, of which the defaults are:

{
  extensions: ['.png', '.jpg'],
  filePrefix: 'img/img-',
  hashLength: 6
}

What it does

Establishes the module exports for the provided file extensions so that requiring those files will return the hashed file path.

Todo

Should leverage webpack config for loader so that exported path matches what's generated by the bundle.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment