babel-plugin-codegen icon indicating copy to clipboard operation
babel-plugin-codegen copied to clipboard

Add support for full module resolution in require & import

Open jesstelford opened this issue 3 years ago • 0 comments

I've created a reusable codegen which works great (thanks for the library!). However, once I published & consume the codegen as an npm module (@ceteio/next-layout-loader), it no longer works:

const Layout = codegen.require("@ceteio/next-layout-loader", __filename);
ModuleBuildError: Module build failed (from ./node_modules/next/dist/build/babel/loader/index.js):
Error: Cannot find module '/sandbox/pages/@ceteio/next-layout-loader'
Require stack:
- /sandbox/node_modules/babel-plugin-codegen/dist/helpers.js

See an example on codesandbox

It looks like the code for loading codegen.require / import statements is hard-coded to assume a relative path is always passed:

https://github.com/kentcdodds/babel-plugin-codegen/blob/664b96c57d1f2ede88acef6da1606df0bcd834bc/src/helpers.ts#L101-L111

Suggested fix

I'm not 100% sure how the lookup is meant to work here, but perhaps this could be replaced with the resolve module to take into account both relative imports and module-style ones?

jesstelford avatar Dec 23 '21 01:12 jesstelford