为什么在TypeScript中进行动态导入时会出现“找不到模块”错误?

huangapple go评论75阅读模式
英文:

Why do I get a "cannot find module" error when doing a dynamic import in TypeScript?

问题

我正在尝试在运行时动态加载JavaScript模块,但遇到问题。我创建了一个非常简单的示例,也许有人可以解释我哪里出错了。

我有一个名为 "testModule.js" 的JavaScript文件,位于 "media" 文件夹中。

const data = { theString: "Hello baby" }

export default data

然后在我的主项目中,我有以下代码:

export class StartImportTest extends Scene
{
    constructor() {
        super()
        var tURL = "media/testModule.js"
        const a = import(tURL).then(this.testImport)
    }
    testImport(a: any) {
        console.log(a, a.theString)
    }
}

当我运行它时,我收到错误消息 无法找到模块 'media/testModule.js'

URL 绝对正确(我尝试从该位置加载图片,一切正常工作),所以也许错误与我的 webpack 设置有关?但我不确定该在那里查找什么。

英文:

I'm trying to load in a JavaScript module dynamically at runtime and it's not playing ball. I've created a very simple barebones example, perhaps someone can explain where I'm going wrong.

I have a javascript file called "testModule.js" sitting in the folder "media".

const data={theString:"Hello baby"}

export default data

Then in my main project I have the following code:

export class StartImportTest extends Scene
{
    constructor() {
        super()
        var tURL = "media/testModule.js"
        const a= import(tURL).then(this.testImport)
    }
    testImport(a:any) {
        console.log(a, a.theString)
    }
}

When I run it, I get the error message Cannot find module 'media/testModule.js'

The url is definitely correct (I tried loading in a picture from that location instead, which worked fine), so perhaps the error is something to do with my webpack settings? But I'm not sure what to look for there.

答案1

得分: 0

要指示模块存在于当前文件夹的子文件夹中,您应该在url模块的路径前面添加./

var tURL = "./media/testModule.js"

如果模块位于不同的文件夹中,那么需要使用../,次数与上级结构一样多,以达到目标文件夹。

更新

Webpack使用这些路径来查找依赖项并构建捆绑包。因此,您应该提供源文件的路径。一旦最终构建完成,这些路径将不会被使用。所以您不用担心。

英文:

To indicate that module exists in a subfolder in the current folder, you should prepend ./ to url module's path

var tURL = "./media/testModule.js"

If module resides in a different folder then need to use ../ as many times as necessary to go up in the structure to get to the destination folder.

update

Webpack uses these paths to find dependencies and to build the bundle. So you should provide paths to the source file. Once the final build is created, these paths won't be used. So you'll be okay.

huangapple
  • 本文由 发表于 2023年6月12日 19:12:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76456101.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定