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.
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.