简体   繁体   中英

how do I export/import a variable in nodejs?

How do I export/import a variable in nodejs?

I've tried export and import but it says that its supposed to be a module and when I change the type to module in the json file it says that require is not defined.

with CommonJS modules (the Node.js default) you can export a variable by assigning to exports , and import it via require() :

// bar.js
exports.variable = 'value';

// foo.js
const { variable } = require('./bar');

if you're using ECMAScript modules, the keywords import and export do these:

// bar.js
export const variable = 'value';

// foo.js
import { variable } from './bar';

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