我有一些JS,可以动态导入并添加一堆这样的路由:
let routeFiles = [
'./routes/projects',
'./routes/scraper',
'./routes/admin',
// etc
]
initRoutes(app) {
for (let fn of routeFiles) {
let routes = require(fn)
app.use('/tix', routes)
}
debug.info('init routes done')
}
但是用打字稿我会出错
An import declaration can only be used in a namespace or module.
环顾四周似乎没有一个明确的答案
const mod = await require(fp)
这给我一个错误,即使我检查了传入的路径,也无法找到模块为.
:
(node:33353) UnhandledPromiseRejectionWarning: Error: Error: Cannot find module "."
at Object.<anonymous> (/Users/dc/dev/tix/recobot/stack/backend/build/server.js:843:23)
at Generator.next (<anonymous>)
at /Users/dc/dev/tix/recobot/stack/backend/build/server.js:800:71
at new Promise (<anonymous>)
at __awaiter (/Users/dc/dev/tix/recobot/stack/backend/build/server.js:796:12)
at Object.initModels (/Users/dc/dev/tix/recobot/stack/backend/build/server.js:821:16)
at Object.<anonymous> (/Users/dc/dev/tix/recobot/stack/backend/build/server.js:527:28)
at Generator.next (<anonymous>)
at fulfilled (/Users/dc/dev/tix/recobot/stack/backend/build/server.js:497:58)
at process._tickCallback (internal/process/next_tick.js:68:7)
我还尝试了令人费解的:
mod = await System.import(fn)
mod.init()
相同错误
Error: Cannot find module './models/Projects'.
如果我将导入提升到主代码块之外,则一切运行正常。
import Project from "./models/Projects"
const TixBot = {
async initModels(dbc: any) {
await Project.init(dbc)
顺便说一句,我正在webpack下运行,出现了这个问题: https://github.com/webpack/webpack/issues/1599
由
解析 node: {
__dirname: true
},
在webpack.config中。男人,有时候我在开发现代JS时会害怕看不起...