Using a class imported with the import function (JavaScript)

この記事は約4分で読めます。
スポンサーリンク

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.

スポンサーリンク

Websites I used as references

import() - JavaScript | MDN
import() 構文は、よくダイナミックインポートと呼ばれますが、非同期かつ動的に、 ECMAScript モジュールを、潜在的にモジュールではない環境に読み込めるようにする関数風の式です。

コメント

タイトルとURLをコピーしました