AskYous
AskYous

Reputation: 4730

ES6 Modules in Chrome & Node... `export function` or `module.exports = function`?

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?

Upvotes: 2

Views: 1697

Answers (2)

kingdaro
kingdaro

Reputation: 12018

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.

Upvotes: 4

SandeliusME
SandeliusME

Reputation: 822

Use Babel and compile your code

Upvotes: 0

Related Questions