模块化

108 阅读1分钟
Es Module in Node.js

module.mjs

export const foo = 'foo'
export const bar = 'bar'

index.js

import { foo, bar } from './module.mjs'
console.log(foo, bar)
// node --experimental-modules index.mjs  启动
import { foo, bar } from './module.mjs'
console.log(foo, bar)

import fs from 'fs'
fs.writeFileSync('./foo.txt', 'es module working')

import _ from 'lodash'
console.log(_.camelCase('ES Module'))

// 第三方模块都是导出默认成员
// import { camelCase } from 'lodash'

// 系统内置模块都做了兼容可以导入(单独导出一次,整体导出一次)
import { writeFileSync } from 'fs'
writeFileSync('./bar.txt', 'bar module working')
Es Module in Node.js与commonjs的交互

commonjs.js

// 不能在commomjs模块中通过require载入ES Module
// module.exports = {
//     foo: 'commonjs exports value'
// }

exports.foo = 'commonjs exports value'

// ESM中没有commonjs这些模块全局成员
console.log(require)
console.log(module)
console.log(exports)
console.log(__filrname)
console.log(__dirname)

es-module.mjs

// commonjs只会导出默认成员,不能直接提取成员,不是解构导出对象
import mod from './commonjs.js'
console.log(mod)
// esm.mjs
import { fileURLToPath } from 'url'
import { dirname } from 'path'
const __fileName = fileURLToPath(import.meta.url)
const dirName = dirName(__fileName)

package.json

// 直接使用js  (commonjs.cjs可以使用commonjs规范)
{
    "type": "module"
}
Es Module in Node.js Babel兼容方案
//  yarn add @babel/node @babel/core @babel/preset-env -- dev
// 命令 yarn babel-node index.js --presets=@babel/preset-env
// .babelrc
"presets": ["@babel/preset-env"]
// yarn remove @babel/preset-env
// yarn add @babel/plugin-transform-modiles-commonjs --dev  删除.babelrc presets