Nodejs 2种模块系统 CommonJS 模块和EcmaScript模块
Nodejs有2种模块系统,CommonJS模块和EcmaScript模块,默认是CommonJS.
下面是官方文档关于模块、默认模块的描述

This flag currently defaults to
"commonjs", but it may change in the future to default to"module". For this reason it is best to be explicit wherever possible; in particular, package authors should always include the"type"field in theirpackage.jsonfiles, even in packages where all sources are CommonJS.

Commonjs 模块用法
commonjs是一个项目来标准化浏览器外的js(如web服务器端、桌面端、命令行端)模块化系统的项目。维基百科是这样定义的,没找到commonjs官网。
commonjs语法,require导入,module.exports导出,看例子
//utils.js
function generateRandomNumber() {
return Math.floor(Math.random() * 100 + 1)
}
module.exports = generateRandomNumber;
//index.js
const generateRandomNumber = require('./utils')
console.log(`Random Number: ${generateRandomNumber()}`)
执行node index, 发现可以打印出一个随机数,说明导入成功了
上面例子只是导出一个函数,如果导出多个怎么写呢
// utils.js
// 生成一个1-100之间的随机整数
function generateRandomNumber() {
return Math.floor(Math.random() * 100 + 1)
}
// 获取今天的日期,格式为"YYYY-MM-DD"
const today = () => {
const today = new Date()
const year = today.getFullYear()
const month = String(today.getMonth() + 1).padStart(2, '0')
const day = String(today.getDate()).padStart(2, '0')
const formattedDate = `${year}-${month}-${day}`
return formattedDate
}
module.exports = {
generateRandomNumber,
today,
}
// index.js
const { generateRandomNumber, today } = require('./utils')
console.log(`Random Number: ${generateRandomNumber()}------today: ${today()}`)

EcmaScript 模块
- 在
nodejs可以用mjs文件来表明是一个esm模块。 - 也可以在
package.json文件来加type: module来表明是esm模块。 用mjs文件来展示esm用法,import导入,export导出
// postController.mjs
const posts = [
{
id: 1,
title: 'Post 1',
content: 'This is the content of post 1',
},
// Add more posts here
{
id: 2,
title: 'Post 2',
content: 'This is the content of post 2',
},
]
export const getPosts = () => posts
// showPost.mjs
import { getPosts } from './postController.mjs'
console.log('getPosts', getPosts())
默认导出和命名导出同时的情况
// postController.mjs
const posts = [
{
id: 1,
title: 'Post 1',
content: 'This is the content of post 1',
},
// Add more posts here
{
id: 2,
title: 'Post 2',
content: 'This is the content of post 2',
},
]
export const getPosts = () => posts
const isObject = val => val !== null && typeof val === 'object'
export default isObject
// showPost.mjs
import isObject, { getPosts } from './postController.mjs'
console.log(`getPosts:`, getPosts())
console.log(
`isObject({day: '五一假期最后一天'}), ${isObject({
day: '五一假期最后一天',
})}`
)

在同一个nodejs项目里可以同时写commonjs和esmjs模块语法吗?答案是可以,比如上面的例子,默认就是commonjs,esm部门用.mjs文件来写,就同时有2种模块语法了。
转载自:https://juejin.cn/post/7364740313284739098