如何将自动导入添加到我的 Koa 应用程序?
当我启动应用程序时,此路径 import { user} from 'models/index.js' 是错误的,但此路径 import { user} from '../../models/index.js' 还可以。当我将鼠标悬停在“models/index.js”上时 我看到像模块“d:/portfolio/сlevertec/app/server/src/models/index”这样的路径并且可以切换,这意味着该路径存在。
文件夹结构:
- server/
- src/
- database/
- postgres/
- index.js
- models/
- index.js
- User.js
- jsconfig.json
- package.json
jsconfig.json在应用程序的根目录中
{
"compilerOptions": {
"baseUrl": "src",
"target": "ES6",
"module": "ES6",
"checkJs": true,
"moduleResolution": "node",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
},
"paths": {
"models/*": ["models/*"]
},
"include": ["src"]
}
src/database/postgres/index.js
import { user} from 'models/index.js'
import sequelize from './instance.js'
const User = sequelize.define('User', user)
src/models/index.js
export { default as user } from './User.js'
使用
exports
定义子路径导出。
package.json
"type": "module",
"exports": {
".": "./src/index.js",
"./*.js": "./src/*.js",
"models/*.js": "./src/models/*.js"
}