我正在尝试导入模块。
渴望:使用require
并且import
不考虑模块类型(module_es6/commonjs)而无需额外的库。
在目录中(图片)demo-*
- 导出
在目录中import-as-*
- 导入目录中的内容demo-*
模块*-commonjs
以样式描述module.exports/require
模块以样式*-module
描述export/import
示例:
// "type": "commonjs"
module.exports = () => {
return "i commonjs"
}
// "type": "module"
export default () => {
return "i module"
}
每个package.json
都有一个相应的属性"type": "module/commonjs"
。例如:
{
"name": "demo-module",
"main": "./index.js",
"type": "module"
}
Node(-v v12.13.0) 以标志开头--experimental-modules
和--es-module-specifier-resolution=node
从import-as-module
一切导入都很好,包括模块demo-commonjs
。
这里 fromimport-as-commonjs
不会从require('../demo-module')
任何东西导入。
Error [ERR_REQUIRE_ESM]:
Must use import to load ES Module: ...path.../demo-module/index.js
如何达到预期的效果?
下面是一个不可能的片段!!!
// + ПРИМЕРЫ ЭКСПОРТА
// demo-commonjs | package.json->{name, main,"type": "commonjs"}
module.exports = () => {
return "i commonjs"
}
// demo-module | package.json->"type": "module"
const CONST_MOD = 'CONST_MOD'
export { CONST_MOD }
export default () => {
return "i module"
}
// + ПРИМЕРЫ ИМПОРТА
// import-as-module | package.json->"type": "module"
import CommonJS from '../demo-commonjs'
console.log(CommonJS())
import def, { CONST_MOD } from '../demo-module'
console.log(def())
console.log(CONST_MOD)
// import-as-commonjs | package.json->"type": "commonjs"
const CommonJS = require('../demo-commonjs')
console.log(CommonJS())
// ЗДЕСЬ ПОЛУЧАЮ ОШИБКУ
try {
var CONST_MOD = require('../demo-module')
}
catch (error) {
console.error(error) // Must use import to load ES Module:
}
console.log(CONST_MOD) // undefined
https://nodejs.org/dist/latest-v12.x/docs/api/esm.html#esm_code_require_code
所以你的愿望是不可能的。