Keywords: Node.js | modules | variable sharing | CommonJS | ES modules
Abstract: This article explores how to share variables between files in Node.js. It first introduces the traditional CommonJS module system using module.exports and require for exporting and importing variables. Then, it details the modern ES module system supported in recent Node.js versions, including setup and usage of import/export. Code examples demonstrate both methods, and common errors like TypeError are analyzed with solutions. Finally, best practices are provided to help developers choose the appropriate module system.
Introduction
In Node.js application development, modularity is a core concept that allows code to be split into reusable files. A common need is to define configuration or variables in one file and use them in another. Based on Stack Overflow Q&A data, this article explains how to achieve this.
CommonJS Module System
Node.js traditionally uses the CommonJS module system. To export a variable, you can use the module.exports object. For example, in the source file sourceFile.js:
const variableName = 'variableValue';
module.exports = variableName;
Or export as an object:
module.exports = { variableName: 'variableValue' };
In the consumer file, use the require function to import:
const importedVariable = require('./sourceFile');
console.log(importedVariable); // outputs: variableValue
If exported as an object, you can destructure:
const { variableName } = require('./sourceFile');
ES Module System
Since Node.js version 8.9.0, ECMAScript modules (ES modules) are supported. To use ES modules, setup is required. For Node v13.9.0 and above, experimental modules are enabled by default; for older versions, use the --experimental-modules flag. File extensions should be .mjs or set "type": "module" in package.json.
In ES modules, use export to export variables:
// named export
export const variableName = 'variableValue';
// default export
export default { variableName: variableName };
Import using import:
// import named export
import { variableName } from './sourceFile.mjs';
console.log(variableName); // outputs: variableValue
// import default export
import sourceFile from './sourceFile.mjs';
console.log(sourceFile.variableName); // outputs: variableValue
You can also import all exports using * as:
import * as allExports from './sourceFile.mjs';
console.log(allExports.variableName); // outputs: variableValue
Error Analysis and Solutions
In the original problem, the error TypeError: Cannot read property 'confvar' of undefined occurs because the variable was not properly exported. In CommonJS, you must set the export object using module.exports. If not set, require returns an empty object, causing property access to fail.
Solution: Ensure the variable is exported in the source file. For example, modify conf.js:
var config = {
'confvar': 'configval'
};
module.exports = config;
Then in the consumer file:
const conf = require('./conf');
const url = conf.confvar; // correct access
Best Practices
When choosing a module system, consider project requirements and Node.js version. For new projects, ES modules are recommended as they align with ECMAScript standards and support static analysis and tree shaking. For existing projects or backward compatibility, CommonJS is a reliable choice. Always explicitly export and import variables, avoid global variables to improve code maintainability.
Additionally, you can use re-export to organize code. For example, export specific parts from multiple modules in a directory index file.