2

I have a module like this:

module.exports = class Edge {
    constructor(vertex1, vertex2) {
        this.vertex1 = vertex1;
        this.vertex2 = vertex2;
    }
}

I want to import it into some NodeJS files and some front-end files in Chrome. I know Chrome now supports ES6 modules, but importing is giving me trouble:

ReferenceError: module is not defined

I think I'm supposed to use export class { ... }, but that's NOT supported in NodeJS right? How can I make this module work with both Chrome and NodeJS?

0

2 Answers 2

4

ES6 modules are currently supported under a flag, so it is possible to have your file work natively in both environments. A few important things to note:

  • In Node, the file has to have an .mjs extension, so Node knows beforehand to load it as an ES module instead of a CommonJS module
  • Browsers don't automatically search for .js or .mjs extensions. You have to add them yourself when importing, e.g. import { Edge } from './edge.mjs'

However, the technology is still new and experimental, and there's not a lot of documentation or material on the subject. That, and relying on native technology isn't a good idea if you want to support older node environments and browsers.

If you want to support older environments, you can use a tool like webpack to "bundle" up your files into one big JS file that any environment can run.

Lastly, look more into ES modules and gain a good understanding of how the syntax works in detail (defaults especially), so you'll run into less problems later.

Sign up to request clarification or add additional context in comments.

1 Comment

It should be "ES6 modules are currently supported under a flag". Node has always supported "NodeJS modules".
0

Use Babel and compile your code

4 Comments

Is the only way to use a compiler?
Ok. What would Babel do (I never used it)? Would it make a version for Node and a version for Chrome? 2 files?
Babel would translate the ES6 import/export statements into CommonJS to allow them to run in Node. However you wouldn't run babel for chrome, since chrome supports the ES6 syntax natively.
Also the NPM developers have come up with a new proposal for the module system in node so it will prob take some time before it gets accepted. Babel is the only way to go atm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.