swc-project / pkgs

node.js packages for SWC
59 stars 19 forks source link

__webpack_require__(...).context is not a function #8

Open thatsmydoing opened 1 year ago

thatsmydoing commented 1 year ago

From https://github.com/swc-project/swc-loader/issues/64#issue-1335268930 by @callmeteus

I'm trying to port from babel-loader and ts-loader to swc-loader, but everytime require.context is called, it returns undefined.

When printing the require variable, it returns the following module:

function webpackEmptyContext(req) {
  var e = new Error("Cannot find module '" + req + "'");
  e.code = 'MODULE_NOT_FOUND';
  throw e;
}
webpackEmptyContext.keys = () => ([]);
webpackEmptyContext.resolve = webpackEmptyContext;
webpackEmptyContext.id = 5102;
module.exports = webpackEmptyContext;
thatsmydoing commented 1 year ago

The issue we've found here is when the regexp passed to require.context uses a lookbehind expression like /(?<!.spec).(js|tsx)$/, swc transforms it to RegExp("(?<!.spec).(js|tsx)$"). Playground

webpack only processes require.context if the provided regex is a literal and otherwise skips it. So in our case, removing the lookbehind made swc keep it as a literal and it worked for us. Another option is to set the target to ES2022 (if the project allows) where swc will keep it as a literal too.

Though it would be nice if swc-loader could be smart about this and not transform require.context arguments but I'm not sure how feasible that is.