简体   繁体   中英

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?

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, eg 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.

Use Babel and compile your code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM