diff --git a/1-js/13-modules/03-modules-dynamic-imports/article.md b/1-js/13-modules/03-modules-dynamic-imports/article.md index e48144a3e..939af87f2 100644 --- a/1-js/13-modules/03-modules-dynamic-imports/article.md +++ b/1-js/13-modules/03-modules-dynamic-imports/article.md @@ -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 import in any block + import ...; // Erro, não podemos colocar import em 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? -## The import() expression +## A expressão import() -The `import(module)` expression loads the module and returns a promise that 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 uma promise que é 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 => ) - .catch(err => ) + .then(obj => ) + .catch(err => ) ``` -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'); @@ -64,35 +64,35 @@ hi(); bye(); ``` -Or, if `say.js` has the default export: +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 regular scripts, they don't require `script type="module"`. +Importações dinâmicas funcionam em scripts 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. ``` diff --git a/1-js/13-modules/03-modules-dynamic-imports/say.view/index.html b/1-js/13-modules/03-modules-dynamic-imports/say.view/index.html index 80909cf94..7f29ae67d 100644 --- a/1-js/13-modules/03-modules-dynamic-imports/say.view/index.html +++ b/1-js/13-modules/03-modules-dynamic-imports/say.view/index.html @@ -2,9 +2,9 @@ diff --git a/1-js/13-modules/03-modules-dynamic-imports/say.view/say.js b/1-js/13-modules/03-modules-dynamic-imports/say.view/say.js index cff234b7c..e99bf388f 100644 --- a/1-js/13-modules/03-modules-dynamic-imports/say.view/say.js +++ b/1-js/13-modules/03-modules-dynamic-imports/say.view/say.js @@ -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)!"); }