翻譯不完整。請協助 翻譯此英文文件

import 宣告用於引入由另一個模塊所導出的綁定。被引入的模塊,無論是否宣告strict mode,都會處於該模式。import 宣告無法用於嵌入式腳本(embedded scripts)。

語法

import defaultExport from "module-name";
import * as name from "module-name";
import { export } from "module-name";
import { export as alias } from "module-name";
import { export1 , export2 } from "module-name";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name";
defaultExport
從模塊要參照過去的預設導出名。
module-name
要導入的模塊名。通常包含 .js 模塊文件的相對或絕對路徑名。請確認你的開發環境,某些bundler 會允許或要求你加入副檔名。只允許使用單引號和雙引號字符串。
name
參照導入時,會用做 namespace 種類的模塊名。
export, exportN
導出要被引入時,要用的名號。
alias, aliasN
別名,重新命名被import進來的js稱呼。

敘述

name 參數能將模塊物件(module object)名用於 namespace 種類,以便各導出能參照之。export 參數會在引用 import * as name 語法時,指定 individual named export。以下示例將展示語法的簡例。

引入整個模塊

本例在當前作用域插入了 myModule 變數,並把所有來自 /modules/my-module.js 檔案的模塊導出。

import * as myModule from '/modules/my-module.js';

Here, accessing the exports means using the module name ("myModule" in this case) as a namespace. For example, if the module imported above includes an export doAllTheAmazingThings(), you would call it like this:

myModule.doAllTheAmazingThings();

從模塊引入單一導出

給定由 my-module 導出的模塊,稱作 myExport 物件與數值,無論是顯性(因為整個模塊被導出了)與隱性(使用 export 宣告),這裡就在當前的作用域插入 myExport

import {myExport} from '/modules/my-module.js';

從模塊引入數個導出

例在當前作用域插入了 foobar

import {foo, bar} from '/modules/my-module.js';

使用便利的 alias 引入或導出

在引入時,可以重新命名導出的模塊。例如說,這裡就就在目前作用域插入 shortName 變數。

import {reallyReallyLongModuleExportName as shortName}
  from '/modules/my-module.js';

Rename multiple exports during import

使用別名(aliases)以便引入或導出模塊

import {
  reallyReallyLongModuleExportName as shortName,
  anotherLongModuleName as short
} from '/modules/my-module.js';

Import a module for its side effects only

Import an entire module for side effects only, without importing anything. This runs the module's global code, but doesn't actually import any values.

import '/modules/my-module.js';

引入預設

你可以引入預設好的 export,無論他屬於物件、函式、還是類別。import 宣告可以接著引入該預設。

最簡單的預設引入:

import myDefault from '/modules/my-module.js';

It is also possible to use the default syntax with the ones seen above (namespace imports or named imports). In such cases, the default import will have to be declared first. For instance:

import myDefault, * as myModule from '/modules/my-module.js';
// myModule used as a namespace

或是:

import myDefault, {foo, bar} from '/modules/my-module.js';
// specific, named imports

動態引入

import 關鍵字也能透過函式呼叫引入之。在這種情況下,該函式回傳 promise。

import('/modules/my-module.js')
  .then((module) => {
    // 在模塊內作點事情
  });

這方法也支援關鍵字 await。

let module = await import('/modules/my-module.js');

示例

引用次要模塊以協助程式執行 AJAX JSON 請求。

模塊:file.js

function getJSON(url, callback) {
  let xhr = new XMLHttpRequest();
  xhr.onload = function () { 
    callback(this.responseText) 
  };
  xhr.open('GET', url, true);
  xhr.send();
}

export function getUsefulContents(url, callback) {
  getJSON(url, data => callback(JSON.parse(data)));
}

主要程式:main.js

import { getUsefulContents } from '/modules/file.js';

getUsefulContents('http://www.example.com',
    data => { doSomethingUseful(data); });

動態引入

This example shows how to load functionality on to a page based on a user action, in this case a button click, and then call a function within that module. This is not the only way to implement this functionality. The import() function also supports await.

const main = document.querySelector("main");
for (const link of document.querySelectorAll("nav > a")) {
  link.addEventListener("click", e => {
    e.preventDefault();

    import('/modules/my-module.js')
      .then(module => {
        module.loadPageInto(main);
      })
      .catch(err => {
        main.textContent = err.message;
      });
  });
}

規範

規範 狀態 註解
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Imports' in that specification.
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
The definition of 'Imports' in that specification.
Draft  

瀏覽器相容性

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung InternetNode.js
Basic supportChrome Full support 61Edge Full support 16
Full support 16
Full support 15
Disabled
Disabled From version 15: this feature is behind the Experimental JavaScript Features preference.
Firefox Full support 60
Full support 60
No support 54 — 60
Disabled
Disabled From version 54 until version 60 (exclusive): this feature is behind the dom.moduleScripts.enabled preference. To change preferences in Firefox, visit about:config.
IE No support NoOpera Full support 47Safari Full support 10.1WebView Android No support NoChrome Android Full support 61Edge Mobile Full support YesFirefox Android Full support 60
Full support 60
No support 54 — 60
Disabled
Disabled From version 54 until version 60 (exclusive): this feature is behind the dom.moduleScripts.enabled preference. To change preferences in Firefox, visit about:config.
Opera Android Full support 47Safari iOS Full support 10.1Samsung Internet Android No support Nonodejs Full support 8.5.0
Notes Disabled
Full support 8.5.0
Notes Disabled
Notes files must have suffix .mjs, not .js
Disabled From version 8.5.0: this feature is behind the --experimental-modules runtime flag.
Dynamic importChrome Full support 63Edge No support No
Notes
No support No
Notes
Notes See development status.
Firefox No support No
Notes
No support No
Notes
Notes See bug 1342012.
IE No support NoOpera Full support 50Safari Full support 11.1WebView Android Full support 63Chrome Android Full support 63Edge Mobile No support NoFirefox Android No support No
Notes
No support No
Notes
Notes See bug 1342012.
Opera Android Full support 50Safari iOS Full support 11.1Samsung Internet Android ? nodejs ?

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown
See implementation notes.
See implementation notes.
User must explicitly enable this feature.
User must explicitly enable this feature.

參見

文件標籤與貢獻者

最近更新: freddy50806,