Skip to content

Instantly share code, notes, and snippets.

@ezidio
Created March 2, 2018 12:01
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ezidio/f64c59d46b19a3fe671a9ded6441de18 to your computer and use it in GitHub Desktop.
Save ezidio/f64c59d46b19a3fe671a9ded6441de18 to your computer and use it in GitHub Desktop.
Jest transformer to work with webpack's require.context
module.exports = {
verbose: true,
moduleDirectories: ['node_modules'],
transform: {
'\\.js$': '<rootDir>/../build/utils/webpack_polyfill'
}
}
module.exports = {
process (src, filename) {
// Return original document if don't have reference to require.context.
if (!/require\.context\(.*\)/gm.test(src)) {
return src
}
return `if (typeof require.context === 'undefined') {
const fs = require('fs')
const path = require('path')
require.context = (base = '.', scanSubDirectories = false, regularExpression = /\.js$/) => {
const files = {}
function readDirectory (directory) {
fs.readdirSync(directory).forEach((file) => {
const fullPath = path.resolve(directory, file)
if (fs.statSync(fullPath).isDirectory()) {
if (scanSubDirectories) readDirectory(fullPath)
return
}
if (!regularExpression.test(fullPath)) return
files[\`./\${file}\`] = true
})
}
readDirectory(path.resolve(__dirname, base))
function Module (file) {
return require(path.resolve(__dirname, base, file))
}
Module.keys = () => Object.keys(files)
return Module
}
}
${src}`
}
}
@sincerekamal
Copy link

where did you configure to use require_context_transform.js?

@pelotom
Copy link

pelotom commented Sep 23, 2018

@sincerekamal I think that was supposed to be named webpack_polyfill.js.

@ajclaasen
Copy link

ajclaasen commented Jun 15, 2022

Note that due to the default value of /\.js$/ of the regularExpression param, this polyfill only matches javascript file types by default.

If you want to change this default, you should modify line 12.

Webpack's default is /^\.\/.*$/1

Footnotes

  1. https://webpack.js.org/guides/dependency-management/#requirecontext

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