Kostyuk Rostyslav
Kostyuk Rostyslav

Reputation: 417

How to import es6 modules with babel-node?

I have some trouble with writing a quick test for my node express application. The problem is: in my server's file I use es6 import to import my custom class. So there is a line like this: import MyClass from 'src/myclass.js';

my test script look like this:

npx babel-node srv/server.js

the error I get is the following:

Syntax error: Unexpected identifier the module name after import is highlighted

So why I am doing that in first place? I've thought it would be nice to test my web application without running code transpiler each time I need to test it.

I already tried to place --experimental-modules in test command, unfortunatelly it didn't work for me. My node version is : 11.14

My entry point is like this

import MyClass form 'src/myclass.js';

var myClass = new MyClass();

my class file is like this

export default MyClass {
 constructor() {
  ...
 }
}

my babel configuration

require('@babel/register')({
    only: [__dirname + '/src', __dirname + '/srv'],
    ignore: [__dirname + 'node_modules'],
    presets: ['@babel/preset-env']
});

var presets = [
    [
        '@babel/preset-env',
        {
            'useBuiltIns': 'entry',
            'corejs': 'core-js@3'
        }
    ]
];

var plugins = [
    [
        'module-resolver',
        {
            'root': ['./src'],
            'alias': {
                'lance': './node_modules/lance-gg/dist'
            }
        }
    ]
];

module.express = {
    presets,
    plugins
};

So I would like to be able to start my node server to test my code without doing code transpilling (I will do it only in case I need a production building of my application).
I couldn't figured out how exactly I can do that. I would appreciate any help or link to some sort of manual.

Upvotes: 1

Views: 717

Answers (1)

Kostyuk Rostyslav
Kostyuk Rostyslav

Reputation: 417

Hi there I don't understand why but rewriting my babel configuration like this, things start to work:

require('@babel/register')({
    only: [__dirname + '/src', __dirname + '/srv'],
    ignore: [__dirname + 'node_modules'],
    presets: ['@babel/preset-env']
});

var presets = [
    [
        '@babel/preset-env',
        {
            'useBuiltIns': 'entry',
            'corejs': 'core-js@3'
        }
    ]
];

var plugins = [
    [
        'module-resolver',
        {
            'root': ['./src'],
            'alias': {
                'lance': './node_modules/lance-gg/dist'
            }
        }
    ]
];

module.exports = function (api) {
    api.cache(false);

    return {
        presets,
        plugins
    };
};

I will not accept my answer, hopping someone will give me better explanation about why my previous configuration wasn't good enough, but I leave it here maybe it will be useful for someone.

Upvotes: 0

Related Questions