如何在Node.js ES6模块中像React Native一样导入文件夹作为模块?
问题
学习Express时尝试使用ES6模块语法(不使用require)导入模块,遇到目录导入报错。项目目录结构、各文件内容及运行错误如下:
项目目录结构
. ├── app.js ├── package.json └── tt └── index.js
app.js内容
import f from "./tt";
tt/index.js内容
export default function tt() { console.log("tt"); }
package.json内容
{ "name": "hehe", "version": "1.0.0", "description": "", "main": "app.js", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" }
运行报错信息
执行node app.js时出现以下错误:
node:internal/process/esm_loader:97 internalBinding('errors').triggerUncaughtException( ^ Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import '/mnt/devv/rootdir/tt' is not supported resolving ES modules imported from /mnt/devv/rootdir/app.js
目前只有导入./tt/index.js才能正常运行,想知道能否实现像React Native那样,仅导入文件夹即可自动加载其index.js文件。
解决方案
Node.js的ESM模块系统默认不支持自动解析目录下的index.js,但可以通过以下几种方式实现需求:
使用实验性解析标志启动Node.js
添加--experimental-specifier-resolution=node参数,启用类似CommonJS的目录解析规则,运行命令:node --experimental-specifier-resolution=node app.js此时即可直接用
import f from "./tt";导入目录。注意该特性为实验性,未来版本可能有调整,但Node.js 16+版本可正常使用。在子目录添加package.json指定入口
在tt目录下创建package.json文件,通过main或exports字段指定入口文件:{ "main": "index.js", "type": "module" }或更规范的
exports写法:{ "exports": "./index.js" }配置完成后,直接导入
./tt即可自动加载index.js。自定义ESM Loader(进阶)
若需要更灵活的解析规则,可编写自定义Loader实现目录自动解析,但该方法复杂度较高,一般前两种方案足以满足需求。
内容的提问来源于stack exchange,提问作者Muhib Al Hasan
相关产品推荐
相关产品推荐

