-1

I have some es6 modules I would like to unit test in node. Renaming all the files to .mjs is not a workable option.

For simplicity, let's say I have a file like this mymodule.js that has these contents:

export default {
  saySomething: function () { console.log("something"); }
}

And I want to write a simple script to test it like this test.js with these contents:

import { saySomething } from './mymodule';
saySomething();

I'm really not looking to learn Babel at this point. I just need some simple, clear instruction like:

  • Create a .babelrc that contains <blahblah>
  • install such-and-such
  • then run npx babel test.js (or whatever)

I searched around and kept finding a bunch of long tutorials about loading babel modules and what not.

I'm just looking for an expedient recipe--an incantation--not an explanation. Surely that's available somewhere; I just can't find it. any help?

Update

A reply below says no transpilation is necessary because node understands ES6 automatically. I'm willing that I'm just misunderstanding, but when I run this exact example using Node v11.12.0, I get the following error:

$ node test.js

/home/usr/test/test.js:1
import { saySomething } from './mymodule';
       ^

SyntaxError: Unexpected token {
    at Module._compile (internal/modules/cjs/loader.js:743:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:810:10)
    at Module.load (internal/modules/cjs/loader.js:666:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:606:12)
    at Function.Module._load (internal/modules/cjs/loader.js:598:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:862:12)
    at internal/main/run_main_module.js:21:11
Sir Robert
  • 4,686
  • 7
  • 41
  • 57

1 Answers1

0

I think you're misunderstanding something here. ES6 code that you want to execute in node.js does not need to be babel-transpiled at all. Node natively understands ES6. You'd only have to transpile it if you wanted to run it in a browser.

Chris Eff
  • 36
  • 4
  • Maybe I am; I'm willing. But if I use the exact example I posted (using node v11.12.0) I get the error: ... import { saySomething } from './mymodule'; SyntaxError: Unexpected token { at Module._compile (internal/modules/cjs/loader.js:743:23) ... Updating the post to say the same. – Sir Robert Mar 28 '19 at 21:55
  • Damnit! You're right. Node does indeed not support the import/export syntax yet. :-( – Chris Eff Mar 28 '19 at 22:18