我试图从目录中导入模块并捕获错误。
Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import 'C:\js\tg_bot\constants' is not supported resolving ES modules imported from C:\js\tg_bot\index.js
Did you mean to import ../constants/index.js?
package.json
{
"name": "tgbot",
"type": "module",
"private": true,
"scripts": {
"start": "nodemon index.js"
},
"dependencies": {
"@grammyjs/menu": "^1.0.4",
"dotenv": "^16.0.0",
"grammy": "^1.7.0",
"telegraf": "^4.7.0",
"telegram-bot-api": "^2.0.1"
}
}
index.js
import {MSGS, KEYBOARD} from './constants';
console.log(MSGS)
constants/index.js
export { default as KEYBOARD } from './KEYBOARDS';
export { default as MSGS } from './MSGS';
constants/MSGS.js
export const MSGS = {
START: 'My msg'
}
export default MSGS
命令行
node index.js
文件结构:
/constants/index.js
/constants/KEYBOARD.js
/constants/MSGS.js
/index.js
...
我对babel有一些想法,但从未使用过它。 在使用create-react-app建立的React项目中,一切工作得很完美。 请帮忙:)
/constants/index.js
导出吗? - Luigi Minardiconstants
目录中是否有package.json
文件?如果有,请展示出来。如果constants
目录中没有package.json
文件,则您需要添加一个或者导入一个明确的文件名,而不是一个目录。与 CommonJS 不同,ESM 导入在给定目录时不会暗示某些文件名。它要么使用该目录中package.json
文件的主入口点,要么您必须指定要导入的完整文件名。它不会像 CommonJS 一样自动默认为index.js
。 - jfriend00constants/index.js
导出,例如export * from './KEYBOARD.js'
或export {default} from './KEYBOARDS.js'
。这样当您尝试访问'./constants'
时,节点将查找constants/index.js
并找到它。 - Luigi Minardi