0
点赞
收藏
分享

微信扫一扫

commonjs和esmodule

雨鸣静声 03-12 22:00 阅读 3

commonjs的模块导出和引用写法:

lib.js 导出一个模块

let a = 1
let b = 2
function aPlus1() {
  return a++
}
module.exports = {
  a,b,aPlus1
}

index.js引用一个模块

const {a,b,aPlus1} = require('./lib.js')
console.log('hh:',a)

esmodule的模块导出和引用方法:

lib.mjs

export let a = 1
export let b = 2

index.mjs

import {a,b} from './lib.mjs'

console.log(a)
console.log(b)

总结

commonjs使用require关键字来导入模块,使用module.exports来导出模块。

esmodule使用import {a} from './lib.mjs'来导入模块,使用export来导出模块。

存在的区别:

  • 模块加载和执行的时间点不同。CommonJS的模块在运行时加载和执行,而ES Module的模块在编译时就已经加载和执行。
  • 模块导出和导入的方式不同。CommonJS使用module.exports导出模块的输出,使用require导入其他模块。导出时,通常是创建一个值的副本,导入时,这个副本被修改不会影响导出的值。而ES Module使用export导出模块的输出,使用import导入其他模块。导出时,创建的是值的引用,因此对导出值的任何修改都会反映在导入模块中。
  • 模块作用域不同。在CommonJS中,模块内的代码运行在顶层作用域中,可能会污染全局作用域。而ES Module则为每个模块创建一个独立的作用域,避免全局作用域的污染。
举报

相关推荐

0 条评论