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';

Leave a Reply

Your email address will not be published. Required fields are marked *