Velidan
Velidan

Reputation: 6019

Transpile ES6 nested node_modules dependency of the top level node_modules dependency

I have a dependency in my node_modules in ES6 format and it has its nested node_modules dependency is the ES6 format as well.

I managed how to include the top level dependency eg dependencyA into the babel config and transpile it as the project code as well. But how to do it if this dependency has other dependencies in the ES6 format? So: how to configure babel/webpack to transpile the nested node_modules dependency?

Here is the structure

Project (Babel/Webpack/Typescript)
 - node_modules
   - dependencyA (ES6) // ok, added top level ES6 dep to babel transpilation
     - node_modules
       - nested_dependency (ES6) // what to do with that?

Should I go deeper and manually include such a nested node_modules package as well?

eg. babel.config.js

const path = require('path');
module.exports = function (api) {
  api.cache(true);
  return {
    sourceMaps: true,

    include: [
      path.resolve('src'),
      path.resolve('node_modules/dependencyA'), // ok, added top level ES6 dep

      path.resolve('node_modules/dependencyA/node_modules/nested_dependency'), // should I do that?
    ],
    presets: [
      '@babel/preset-env',
      '@babel/preset-react',
      '@babel/preset-flow',
      '@babel/preset-typescript',
    ],
  .....

it looks a bit redundant. Is there exist a way to handle it? Thanks for any help!

Upvotes: 1

Views: 1037

Answers (1)

felixmosh
felixmosh

Reputation: 35473

There is cool way to do this using regex negative look a head.

The syntax is: X(?!Y), it means "search X, but only if not followed by Y".

Let's say that you know which node_modules deps (on the first level) you want to transpile.

You can specify this regex /(dep1|dep2)[\\/](?!.*node_modules)/.

const PATH_DELIMITER = '[\\\\/]'; // match 2 antislashes or one slash
const safePath = (module) => module.split('/').join(PATH_DELIMITER);

const generateIncludes = (modules) => {
  return [
    new RegExp(`(${modules.map(safePath).join('|')})$`),
    new RegExp(`(${modules.map(safePath).join('|')})${PATH_DELIMITER}(?!.*node_modules)`)
  ];
};

const generateExcludes = (modules) => {
  return [
    new RegExp(
      `node_modules${PATH_DELIMITER}(?!(${modules.map(safePath).join('|')})(${PATH_DELIMITER}|$)(?!.*node_modules))`
    )
  ];
};

This code is taken from next-transpile-modules.

This 2 functions should be called with an array of modules that you need to transpile, and pass it to include & exclude

Upvotes: 2

Related Questions