Resolving 'ReferenceError: module is not defined' in Node.js: Proper Use of ES Modules

Dec 08, 2025 · Programming · 9 views · 7.8

Keywords: JavaScript | Node.js | ES Modules | CommonJS | Error Fix

Abstract: This article addresses common module import/export errors in Node.js development. When using ES modules, mixing CommonJS syntax can lead to 'ReferenceError: module is not defined'. It analyzes the cause and provides solutions for correct configuration and usage of ES modules.

Introduction

In Node.js applications, developers may encounter module import/export errors. For example, a user reported the following issue: first, when trying to run a web app, a SyntaxError occurred, indicating that import statements cannot be used outside a module. Later, after enabling ES module support by setting "type": "module" in package.json, a ReferenceError: module is not defined appeared.

Error Analysis

The initial SyntaxError is due to Node.js defaulting to the CommonJS module system, while the code uses ES module import statements. To use ES modules, it is necessary to add "type": "module" in package.json or use the .mjs extension. However, after enabling ES modules, the code still uses CommonJS export syntax module.exports = api;. In an ES module environment, the module object is not defined, thus throwing a ReferenceError.

Solution

Based on the best answer, the solution is to replace CommonJS export with ES module export. Specifically, change module.exports = api; to export default api;. This way, in ES modules, export default is used to export the default value, avoiding the ReferenceError.

Corrected code snippet:

// Other import statements...
api.listen(process.env.PORT, error => {
    // Code logic
});

export default api;

With this modification, the code will fully comply with ES module specifications, resolving the error.

In-depth Discussion

ES modules are part of the ECMAScript standard and have been enabled by default since Node.js v13.2.0. Compared to CommonJS, ES modules provide static import and export, aiding optimization and toolchain support. In mixed projects, it is important to unify the module system to avoid syntax conflicts. Additionally, the "exports" field in package.json can be configured to manage module entry points.

Conclusion

In summary, when using ES modules in Node.js, ensure all imports and exports follow ES module syntax. Avoid mixing CommonJS require and module.exports. Through proper configuration and code adjustments, errors such as 'ReferenceError: module is not defined' can be effectively resolved, improving development efficiency.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.