Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Dynamic imports#419

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 29 additions & 29 deletions1-js/13-modules/03-modules-dynamic-imports/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,61 @@
#Dynamic imports
#Importações dinâmicas

Export and import statements that we covered in previous chapters are called "static".The syntax is very simple and strict.
As declarações de importação e exportação que abordamos nos capítulos anteriores são chamadas de "estáticas".A sintaxe é bem simples e rígida.

First, we can't dynamically generate any parameters of `import`.
Primeiro, não podemos gerar dinamicamente quaisquer parâmetros de `import`.

The module path must be a primitive string, can't be a function call. This won't work:
O caminho do módulo deve ser uma string primitiva, não pode ser uma chamada de função. Isso não funcionará:

```js
import ... from *!*getModuleName()*/!*; //Error, only from"string"is allowed
import ... from *!*getModuleName()*/!*; //Erro, apenas a partir de"string"é permitido
```

Second, we can't import conditionally or at run-time:
Segundo, não podemos importar condicionalmente ou em tempo de execução:

```js
if(...) {
import ...; //Error, not allowed!
import ...; //Erro, não permitido!
}

{
import ...; //Error, we can't put importin any block
import ...; //Erro, não podemos colocar importem qualquer bloco
}
```

That's because`import`/`export`aim to provide a backbone for the code structure. That's a good thing, as code structure can be analyzed, modules can be gathered and bundled into one file by special tools, unused exports can be removed("tree-shaken").That's possible only because the structure of imports/exports is simple and fixed.
Isso ocorre porque`import`/`export`têm como objetivo fornecer uma estrutura básica para a organização do código. Isso é positivo, pois a estrutura do código pode ser analisada, os módulos podem ser reunidos e agrupados em um único arquivo por ferramentas especiais, e as exportações não utilizadas podem ser removidas("tree-shaken").Isso é possível apenas porque a estrutura de importações/exportações é simples e fixa.

But how can we import a module dynamically, on-demand?
Mas como podemos importar um módulo dinamicamente, sob demanda?

##Theimport() expression
##A expressãoimport()

The`import(module)`expression loads the module and returns apromisethat resolves into a module object that contains all its exports. It can be called from any place in the code.
A expressão`import(módulo)`carrega o módulo e retorna umapromiseque é resolvida para um objeto de módulo contendo todas as suas exportações. Pode ser chamado de qualquer lugar no código.

We can use it dynamically in any place of the code, for instance:
Podemos utilizá-lo dinamicamente em qualquer lugar do código, por exemplo:

```js
let modulePath = prompt("Which module to load?");
let modulePath = prompt("Qual módulo carregar?");

import(modulePath)
.then(obj => <module object>)
.catch(err => <loading error, e.g. if no such module>)
.then(obj => <objeto de módulo>)
.catch(err => <Erro de carregamento, por exemplo, se o módulo não existir>)
```

Or, we could use`let module = await import(modulePath)`if inside an async function.
Ou, poderíamos usar`let module = await import(caminhoDoModulo)`se estiver dentro de uma função assíncrona.

For instance, if we have the following module `say.js`:
Por exemplo, se temos o seguinte módulo `say.js`:

```js
// 📁 say.js
export function hi() {
alert(`Hello`);
alert(`Olá`);
}

export function bye() {
alert(`Bye`);
alert(`Adeus`);
}
```

...Then dynamic import can be like this:
...Então a importação dinâmica pode ser assim:

```js
let {hi, bye} = await import('./say.js');
Expand All@@ -64,35 +64,35 @@ hi();
bye();
```

Or, if `say.js`has the defaultexport:
Ou, se `say.js`tiver o `export default`

```js
// 📁 say.js
export default function() {
alert("Module loaded (export default)!");
alert("Módulo carregado (export default)!");
}
```

...Then, in order to access it, we can use`default`property of the module object:
...Então, para acessá-lo, podemos usar a propriedade`default`do objeto do módulo:

```js
let obj = await import('./say.js');
let say = obj.default;
//or, in one line: let {default: say} = await import('./say.js');
//Ou, em uma linha: let {default: say} = await import('./say.js');

say();
```

Here's the full example:
Aqui está o exemplo completo:

[codetabs src="say" current="index.html"]

```smart
Dynamic imports work in regularscripts, they don't require `script type="module"`.
Importações dinâmicas funcionam emscripts regulares, não requerem `script type="module"`.
```

```smart
Although `import()`looks like a function call, it's a special syntax that just happens to use parentheses (similar to `super()`).
Embora `import()`pareça uma chamada de função, é uma sintaxe especial que, por acaso, utiliza parênteses (semelhante a `super()`).

So we can't copy `import`to a variable or use `call/apply`with it. It's not a function.
Portanto, não podemos copiar `import`para uma variável ou usar `call/apply`com ele. Não é uma função.
```
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,9 +2,9 @@
<script>
asyncfunctionload(){
letsay=awaitimport('./say.js');
say.hi();//Hello!
say.bye();//Bye!
say.default();//Module loaded (export default)!
say.hi();//Olá!
say.bye();//Adeus!
say.default();//Módulo carregado (exportação padrão)!
}
</script>
<buttononclick="load()">Click me</button>
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
export function hi() {
alert(`Hello`);
alert(`Olá!`);
}

export function bye() {
alert(`Bye`);
alert(`Adeus!`);
}

export default function() {
alert("Module loaded (export default)!");
alert("Módulo carregado (exportação padrão)!");
}

[8]ページ先頭

©2009-2025 Movatter.jp