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 ?
1 Answer 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
2 Comments
const http = require("http") in your index.mjs, then I got an error : ReferenceError: require is not defined
type="module"from 'package.json` and try again ?