Things I want to do
When you want to load a module in Dynamic, you load it using an import function instead of an import statement. However, simply writing it that way didn’t work as expected.
We will fix it so that it works.
premise
Before revision
Replace the following import statement with an import function statement.
import { myClass } from './myClass.js';The myClass class is loaded from myClass.js.
Bad example
I tried the following code, but it didn’t work.
const myClass= import ('./myClass.js')Working code
To put it simply, if you do the following, the same value as before the modification will be entered into myClass.
const myClass= (await import('./myClass.js'))['myClass'];Explanation
Now, let’s explain why it didn’t work in the bad example.
This is because you are misunderstanding the return value of import() twice.
The first misconception is that import() is an async function and its return value is a promise.
Therefore, I added `await` to make it synchronous. (Of course, there’s no problem with receiving the return value with `then`.)
Based on the above, the corrected code is as follows, but it still doesn’t work.
const myClass= await import('./myClass.js');Here’s the second misunderstanding.
This is because the promise above returns an object containing all exports, not just the desired class. (It will be packed regardless of whether there is even one export.)
Therefore, as follows:[‘myClass’]You need to specify the required class name.
const myClass= (await import('./myClass.js'))['myClass'];Result
I was able to replace the import statement with an import function.


コメント