Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conflicting use of babel/register

I'm having what appears to be a conflict in babel/register between two local npm packages.

In a package I am doing the following:

require('babel/register');
require('index');

And in the index file of the same package:

require('test');

And in the "test" package:

require('babel/register');
require('test/index');

This throws the following error:

throw new Error("only one instance of babel/polyfill is allowed");

But if I take the babel/register line out of the "test" package, I get the following error in the index file of the "test" package:

import fs from 'fs';
^^^^^^
SyntaxError: Unexpected reserved word

I have tried using System.import to import the "test" package as well (using the polyfill specified on the BabelJS site), but in this context, I get the same error as above. How should I go about importing one package into the other and preserve the ability to use ES6 imports/exports and other ES6 features?

EDIT: I've simplified this a little, I am still requiring the "test" into to the first package, but I am not loading an intermediary file. Instead, the "main" file of "test is set to test/index. Theoretically, now it is just loading a single ES6 module, which it should be able to register. I still get the above error.

like image 548
BTC Avatar asked Jul 08 '15 02:07

BTC


2 Answers

As you have seen, babel/register is only meant to be run once per application, and generally that would be the top-level application that you are starting.

The issue you are facing is that by default, require('babel/register') will only set up your system to transpile files directly inside the module, it will not process node_modules. The expectation generally that anything in node_modules will have been compiled ahead of time when published to your module registry.

One option is to pass ignore: false as an option, e.g. require('babel/register')({ignore: false}); however this is generally a bad idea and can lead to other problems. That will make Babel transpile all files, but that is not always a safe things to do because not all JavaScript code is guaranteed to be a valid ES6 module.

The best solution would be to transpile your test module ahead of time. If that isn't going to work however, you can use the only option to specify a regex or glob for the paths that should be transpiled.

like image 188
loganfsmyth Avatar answered Dec 04 '22 15:12

loganfsmyth


In my case, I got away with setting:

self._babelPolyfill = false;

I don't know if setting the polyfill a second time will cause some subtle problems, but with a good number of unit tests, I didn't see any problems by using this hack to avoid the script choking.

like image 22
Brett Zamir Avatar answered Dec 04 '22 15:12

Brett Zamir