0

I don't get the logic of the module conception in nodejs / javascript

Here is my file : circle.js

const circleArea = r => 3.14 * (r ** 2);
const squareArea = s => s * s;
export {circleArea, squareArea};

file testCircle.js

import { circleArea as circle, squareArea } from "./circle.js"
console.log(squareArea(2));

When I run the program node testCircle.js

SyntaxError: Cannot use import statement outside a module

I have found an explanation here :

SyntaxError: Cannot use import statement outside a module

So In have updated my package.json

  "type": "module"

And it works

BUT

then when I want to run another file which require :

const http = require("http");

I got this new error :

ReferenceError: require is not defined

Is there a way to work with both import and require ?

luk2302
  • 55,258
  • 23
  • 97
  • 137
fransua
  • 501
  • 2
  • 18

1 Answers1

1

Use the extension mjs for ES6 modules without "type": "module" or cjs for Common JS modules with "type": "module". Then you can use both types of modules in one project.

Example 1:

package.json:

{
  "name": "node-starter",
  "version": "0.0.0",
  "scripts": {
    "start": "node index.js"
  },
  "type": "module"
}

index.js:

import { a } from './a.cjs';

a();

a.cjs:

module.exports = {
  a() {
    console.log('Hello World!');
  },
};

Running example: https://stackblitz.com/edit/node-dar2r5

Example 2:

package.json:

{
  "name": "node-starter",
  "version": "0.0.0",
  "scripts": {
    "start": "node index.mjs"
  }
}

index.mjs:

import { a } from './a.js';

a();

a.js:

module.exports = {
  a() {
    console.log('Hello World!');
  },
};

Running example: https://stackblitz.com/edit/node-enengw

jabaa
  • 5,844
  • 3
  • 9
  • 30
  • If I add `const http = require("http")` in your index.mjs, then I got an error : _ReferenceError: require is not defined_ – fransua Aug 02 '22 at 09:10
  • 1
    @fransua A file is either a CommonJS module or a ES6 module. You can't use `require` in a ES6 module and you can't use `import` in a CommonJS module. That means you can't mix `require` and `import` in the same file. Use `import http from "http";` instead – jabaa Aug 02 '22 at 10:45