Including node_modules in Babel

2019-07-29 08:53发布

问题:

I am trying to include my node_modules so that Babel transpiles them along with my src files.

The background of this is this: I have a monorepo with multiple packages, but I do not want to setup a Webpack/ Babel thing for every single package. So my idea was to tell Webpack/ Babel in my main project to transpile its node_modules that are imported by my sources.

I read for this I need to do this to tell Babel to not ignore my node_modules:

require('babel-register')({
  ignore: false
});

Now this gives me errors because there are a lot of packages that are not mine and that don't play along with Babel. But I can also tell Babel to only include specific packages, which I do like this:

require('babel-register')({
  only: /@elmc/
});

Because my packages are scoped under @elmc/package-name. This solves the issue above but now my own package still won't get transpiled. I get an error saying:

.-collection-browser/CollectionBrowser.js Module parse failed: Unexpected token (23:13) You may need an appropriate loader to handle this file type.

|   render() {
|       return <div>asd</div>;
|   }

He doesn't seem to transpile my JSX and instead throws an error. I put my babel-register call in my Webpack config. I got my Webpack config from create-react-app so it is quite lengthy, but here it is in its entirety:

https://gist.github.com/LukasBombach/fe84a563ec9268dee32204d429763d5b

回答1:

Ok I got it working now, this comment explained it:

https://github.com/lerna/lerna/issues/487#issuecomment-302341620

  1. Set resolve.symlinks to false. This is needed for the next step.
  2. Add /@foo/ regex to the include array of the rule that uses babel-loader. Since we turned off symlinks resolving in the previous point, other packages from the monorepo are going to resolve to node_modules/@foo/, not ../. This was suggested in next.js issue, so I just went to see how they implemented it and did something similar.
  3. Change node_modules in resolve.modules to path.resolve(__dirname, 'node_modules'). Otherwise webpack 2 tried to require dependencies from the node_modules of local linked packages. But that's probably because I use file:../bar for specifying them in package.json, as I don't publish them anywhere.
  4. Set up Jest to transpile files under the @foo scope. This means adding "transformIgnorePatterns": ["/node_modules/(?!@foo)"] to Jest's configuration. facebook/jest#2550

However, I had to not do step 3 and also this does not work quite well after all because I have to restart my Webpack dev server every time I make changes to my dependencies. So I guess the answer to this question is: "Here is how to do it, but it the only possible result (this solution) does not quite work"