skip to main content

Jixun's Blog 填坑还是开坑,这是个好问题。

Babel 7: Force Transpile of installed package source code

So here is the problem; I have an existing project which installs a private package that uses features not-yet-supported in an old version of node.

And due to the fact that @babel 7 will not transpile any files under node_modules (Maybe I need a file like .babelrc for that package?) regardless of my include or ignore configuration.

Take a bit of time to poke around the babel package; I couldn’t really tell where to patch and searched for node_modules instead. It worked, and here is the patch:

diff --git a/node_modules/@babel/core/lib/config/files/package.js b/node_modules/@babel/core/lib/config/files/package.js
index c0f8988..6dc1208 100644
--- a/node_modules/@babel/core/lib/config/files/package.js
+++ b/node_modules/@babel/core/lib/config/files/package.js
@@ -28,7 +28,7 @@ function findPackageData(filepath) {
 
   let dirname = _path().default.dirname(filepath);
 
-  while (!pkg && _path().default.basename(dirname) !== "node_modules") {
+  while (!pkg) {
     directories.push(dirname);
     pkg = readConfigPackage(_path().default.join(dirname, PACKAGE_FILENAME));

This will of course have some unwanted behaviour: you might just want it to transpile that one or few modules requires this and skip the one already working:

diff --git a/test-package.js b/test-package.js
index 83ad330..0dd644c 100644
--- a/test-package.js
+++ b/test-package.js
@@ -1,6 +1,8 @@
 require('@babel/register')({
        include: [ () => true ],
-       ignore: [ () => false ],
+       ignore: [(name) => name.includes('node_modules') && !['jixun'].every(pkg => {
+               return name.includes(pkg);
+       })],
        cache: false,
 });

A basic POC git repo can be found at JixunMoe/babel-transpile-node_modules-example-1, and it will work as long as @babel/core version stayed the same.

This is not recommended way to enable this feature, the package maintainer should submit pre-transpiled version to prevent the need to configure babel for this trouble.

Creative Commons Licence This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

Comments