Search code examples
node.jsbabeljsbabel-nodebabel-register

How to make babel/register affect on imported files?


Below gulpfile.babel.js runs without error by babel-node gulpfile.babel.js (I know that to execute the gulp task I should to run gulp taskname, but babel-node gulpfile.babel.js is for debugging without running tasks).

require('@babel/register');
import gulp from 'gulp';

gulp.task('default', done => {
  console.log('No problem!');
  done();
});

If to include file (node-modules/my-config-helper/index.js in this example) which also contains import or export keywords, error SyntaxError: Unexpected token export will occur.

require('@babel/register');
import gulp from 'gulp';

import ConfigHelper from 'my-config-helper';

node-modules/my-config-helper/index.js

require('@babel/register');

export default class ConfigHelper {
  constructor() {
    console.log('ConfigHelper: done');
  }
}

Looks like require('@babel/register'); affects only a single file but not to includes. O'K, what should I do? Just install babel-core and babel-register in my-config-helper in not enough.


Solution

  • You need to move the ES syntax into another file, and require that file from your index.js:

    // index.js
    require('@babel/register');
    require("./gulp-stuff"); <-- from this point on - all ES code will be transpiled
    
    // gulp-stuff.js
    import gulp from 'gulp';
    import ConfigHelper from './my-config-helper';
    // ....
    
    
    // my-config-helper.js
    export default class ConfigHelper {
      constructor() {
        console.log('ConfigHelper: done');
      }
    }