Import statement in Node Js

  • Node.js primarily uses CommonJS for module loading, and the `import` statement is not the default way of importing modules in Node.js. Instead, the widely used syntax is the `require` statement. However, ECMAScript modules (ESM) support, including the `import` statement, has been introduced in later versions of Node.js, starting with Node.js 13.2.0. Please check the Node.js documentation or your specific Node.js version for the most up-to-date information.
Here's a brief overview of both approaches:
  • CommonJS (Using `require`): In CommonJS, modules are loaded using the `require` statement. Here's a simple example:


    // moduleA.js
    const message = "Hello from module A!";
    module.exports = message;


    // main.js
    const moduleA = require('./moduleA');
    console.log(moduleA); // Outputs: Hello from module A!

  • In this example, `moduleA` exports a string, and `main.js` imports and uses that exported value using `require`.
  • ECMAScript Modules (Using `import`): With ECMAScript modules (ESM), you can use the `import` statement to import modules. This feature is available in Node.js starting from version 13.2.0. To use ESM, you can use the `.mjs` file extension or set `"type": "module"` in your `package.json`.


    // moduleB.mjs
    const message = "Hello from module B!";
    export { message };


    // main.mjs
    import { message } from './moduleB.mjs';
    console.log(message); // Outputs: Hello from module B!

  • In this example, `moduleB.mjs` exports a value using the `export` statement, and `main.mjs` imports it using the `import` statement.
Important Points:
  • To use ESM in Node.js, you need to either use the .mjs extension for your files or set `"type": "module"` in your `package.json`.
  • When using ESM, you need to be aware of the file extension (.mjs) and the presence of the "type": "module" setting.
  • ESM is still evolving in Node.js, and some features and behaviors may change in future releases.
  • Make sure to refer to the official Node.js documentation or check your specific Node.js version's documentation for accurate and up-to-date information on module loading syntax.

No comments:

Post a Comment