martpie / next-transpile-modules

Next.js plugin to transpile code from node_modules. Please see: https://github.com/martpie/next-transpile-modules/issues/291
MIT License
1.13k stars 85 forks source link

Automatic externals and aliases based on `peerDependencies` #248

Closed br0p0p closed 1 year ago

br0p0p commented 2 years ago

I quickly threw this together to reduce the amount of custom Webpack config I need to provide in a project I'm working on.

This setExternals option looks for peerDependencies of packages specified in the transpilation list and both adds them to the externals list (when isServer is truthy) and aliases these dependencies to the NextJS app's node_modules instead of the peer dependency's node_modules.

Like I mentioned this was a very quick update and I'm not a Webpack expert so I may have missed something. I'm also happy to change the name of the option from setExternals to something else. (maybe autoExternals is better?)

Example

Say I have a monorepo with a NextJS application (named app) and two other Typescript libraries named foo and bar. app depends on both directly but foo declares bar and react as peerDependencies.

If I enable setExternals and provide the foo and bar packages in the modules list, I don't have to manually specify the react external or alias while also transpilling bar (as it does with foo) instead of treating it like an already transpiled peerDependency.

// app/next.config.js
const withTM = require('next-transpile-modules')(
  ['foo', 'bar'],
  { setExternals: true }
);

Some background

I'm working in a monorepo with multiple apps that depend on other monorepo packages which also sometimes rely on other monorepo packages.

Providing a way to do this automatically saves a lot of manual Webpack config in next.config.js for my setup that would be replicated across many apps. I assume this will be helpful to others with similar setups as well.

krmao commented 2 years ago

very good, hope this auto config by plugin self.

const withTM = require("next-transpile-modules")(["@xx/react-basic", "@xx/basicjs"]);
const withTMPeerDependencies = Object.keys({
    ...require("@xx/basicjs/package.json").peerDependencies,
    ...require("@xx/react-basic/package.json").peerDependencies
});
//region handle next-transpile-modules peerDependencies
if (isServer) config.externals = [...withTMPeerDependencies, ...config.externals];
withTMPeerDependencies.map((denpendency) => {
    config.resolve.alias[denpendency] = path.resolve(__dirname, ".", "node_modules", denpendency);
});
//endregion
martpie commented 2 years ago

Well I'm (very) late to the party.

Thank you very much for this PR.

Could you maybe add the unstable_ prefix to the option as long as we don't have automated tests for those? Then I'll happily merge it :)

martpie commented 1 year ago

cf. pinned issue, closing (thank you for this still!)