简体   繁体   中英

Is there any way I can write “unified” Node.js and browser JS?

Let's say I'm writing an Electron app and I'll be using both Node.js and browser style JavaScript.

Node.js modules have to be written like this:

module.exports = class {
    ...
}

Whereas browser JavaScript modules are written like this:

export default class {
    ...
}

But lets say I want to write module exports that work in both mediums for the same project without code duplication. Is there a way?

Assuming there are no Node.js specific features, even dependencies from many browser-friendly node.js modules should be able to double as browser style code and the other way around. Something like web-pack?

Node.js modules do not need to be written that way. Only modules that still use the legacy commonjs format do.

If you're writing new code, do yourself a favour and add type: "module" to your package.json file, and then just write normal modern JS with import and export . This has been supported in Node since v12 with a runtime flag, and out-of-the-box since v14 (which is the current LTS version).

See https://nodejs.org/api/esm.html for all the details you want to know.

I want to add some extra information, I hope it also could help you.
When you use type: modules in node.js, there are some differences.
Like, you could not use __dirname in node.js with type: modules .
Instead, you need to use import.meta.url as replacement.
You could take a look esm_differences_between_es_modules_and_commonjs for more details.

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