Logo
About JS import and require 引入机制

In both import (ES6 modules) and require (CommonJS), modules can export and import different types of values. However, the way named exports and default exports work is quite different between the two systems. Let’s break it down.

1. Named Exports vs Default Exports

Named Exports (ES6 Modules)

In ES6 modules (import/export), named exports allow you to export multiple variables, functions, or classes by name from a module. When importing them, you must reference their exact name.

Default Exports (ES6 Modules)

ES6 modules also support default exports, which allow you to export a single value or object as the “default” export for that module. You can only have one default export per module.

With default export, you don’t need to use the exact name of the exported variable when importing. You can name it anything.

2. Exports in CommonJS (require)

In CommonJS (the require system), there’s no concept of default exports or named exports the way ES6 modules have. Instead, everything that is exported is assigned to module.exports, and when you require the module, you get whatever object, function, or value is assigned to module.exports.

In CommonJS, the whole module is typically exported as an object, and individual properties of that object are accessed.

Key Differences between import/export (ES6) and require (CommonJS)

1. Exporting and Importing Style:

2. Importing Syntax:

3. Default Exports Handling:

3. Mixing Named and Default Exports

Summary of Differences Between require and import in Exports

Feature import/export (ES6 Modules) require/module.exports (CommonJS)
Named exports Yes, using export {} and import {} Can export an object with named properties
Default export Yes, export default No native concept, but can export a single value
Importing syntax Named exports require {}, default without {} Everything is imported as an object
Mixing named and default Allowed Not directly supported, but can be emulated
Loading type Static (at the beginning of file) Dynamic (can be loaded anywhere in the code)
Flexibility More flexible (named, default, mixed) Less flexible (everything in one export object)

In modern JavaScript, the ES6 module system (import/export) is more powerful and flexible than CommonJS (require/module.exports), which is why it is preferred for most new projects, including in environments like Cocos Creator.