// a.js
class Parrot {
say(){
console.log('Im parrot!')
}
}
module.exports = { Parrot: Parrot }
// index.js
const { Parrot } = require('./a.js')
const myParrot = new Parrot()
myParrot.say() // Im parrot!
(function(exports, require, module, __filename, __dirname) {
class Parrot { }
/** rest code */
});
CJS невомвестим с ESM!
но при сборке можно конвертировать
CJS
ESM
Модули ECMAScript — это официальный стандартный формат упаковки кода JavaScript для повторного использования. Модули определяются с использованием различных операторов import и export.
// addTwo.mjs
function addTwo(num) {
return num + 2;
}
export { addTwo };
// index.(mjs|js)
import {addTwo} from './addTwo.mjs'
addTwo(3) // 5
добавить type:module в package.json
// package.json
{
"name": "myPackage",
"version": "1.0.0",
"type": "module",
"dependencies": {},
"scripts": {}
// rest
}// twoSum.mjs
export function twoSum(a){
return a + 2
}
// index.mjs
async function main(){
if(someCond){
const module = await import('./twoSum.mjs')
const res = module.twoSum(3) // 5
}
}
// car.mjs
class Car {}
export default Car;
// index.mjs
import Car from './car.mjs'
const honda = new Car()
import 'data:text/javascript,console.log("hello!");';
import './02-fn.mjs?query=1#hash=123';
import 'file://full/real/path/to/your/file.mjs'
import.meta.dirname
import.meta.filenameimport.meta.urlimport.meta.resolve(<path>)Доступно через import.meta
// car.cjs
class Car {}
module.exports = {Car}
// index.mjs
import carCJSModule from './car.cjs'
const audi = new carCJSModule.Car()
__filename, __dirname (хотя их можно воссоздать с помощью import.meta.url).require() для импорта модулей в ESM.| ESM | CJS | |
|---|---|---|
| синтаксис | import/export | require/exports |
| динамический | + (возвращает промис) | +- (уже является функцией) |
| default | + | + |
| стандартизирован | да | нет |
| совместим | да | нет, esm не поддерживается |
TC39 - modules
nodejs - esm modules
nodejs - cjs modules