Created
May 10, 2021 18:14
-
-
Save jeremiegirault/11018bc6aec790ca8d3714f5e0a1bd35 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const t = require('@babel/types') | |
// generates "(typeof __webpack_require__ === "function" ? __non_webpack_require__ : require)" | |
const dynamicRequireExpr = () => t.parenthesizedExpression(t.conditionalExpression( | |
t.binaryExpression( | |
'===', | |
// we should look at typeof __non_webpack_require__ but '__webpack_require__' is known at build time and optimized right away | |
t.unaryExpression('typeof', t.identifier('__webpack_require__'), false), | |
t.stringLiteral('function') | |
), | |
t.identifier('__non_webpack_require__'), | |
t.identifier('require'), | |
)) | |
module.exports = function () { | |
return { | |
visitor: { | |
Identifier: function (path) { | |
if (path.node.name === 'require') { | |
if (path.parent?.type === 'CallExpression') { | |
// replace require(x) when is is not known | |
if (path.parent.arguments[0]?.type === 'StringLiteral') { return } | |
path.replaceWith(dynamicRequireExpr()) | |
} | |
// e.g. when using require.resolve or require.cache | |
if (path.parent?.type === 'MemberExpression' && path.parent.object === path.node) { | |
path.replaceWith(dynamicRequireExpr()) | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment