Skip to content

Instantly share code, notes, and snippets.

@wangjing013
Forked from ezidio/jest.config.js
Created December 29, 2020 10:02
Show Gist options
  • Save wangjing013/5fb943faa1e6f1ff11901b5e33d471bd to your computer and use it in GitHub Desktop.
Save wangjing013/5fb943faa1e6f1ff11901b5e33d471bd 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}`
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment