跳至主要內容

匯入元件

由於 webpack,此專案設定支援 ES6 模組。

雖然您仍可以使用 require()module.exports,但我們建議您使用 importexport

例如

Button.js

import React, { Component } from 'react';

class Button extends Component {
render() {
// ...
}
}

export default Button; // Don’t forget to use export default!

DangerButton.js

import React, { Component } from 'react';
import Button from './Button'; // Import a component from another file

class DangerButton extends Component {
render() {
return <Button color="red" />;
}
}

export default DangerButton;

請注意 預設匯出和命名匯出的差異。這是常見的錯誤來源。

當模組只匯出一個項目(例如元件)時,我們建議您堅持使用預設匯入和匯出。當您使用 export default Buttonimport Button from './Button' 時,您便會獲得這樣的結果。

命名匯出適用於匯出多個函式的工具模組。一個模組最多只能有一個預設匯出,以及任意多個命名匯出。

深入了解 ES6 模組

絕對匯入

可將應用程式設定為使用絕對路徑匯入模組。透過在專案根目錄設定 jsconfig.jsontsconfig.json 檔案,即可達成此目的。如果在專案中使用 TypeScript,則專案中應已有一個 tsconfig.json 檔案。

下方為 JavaScript 專案的範例 jsconfig.json 檔案。如果檔案不存在,可自行建立

{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}

如果使用 TypeScript,可設定專案 tsconfig.json 檔案的 compilerOptions 中的 baseUrl 設定。

已為專案設定支援絕對匯入的設定後,若要匯入位於 src/components/Button.js 的模組,可如下方方式匯入模組

import Button from 'components/Button';

更多說明請參閱 jsconfig.json 參考tsconfig.json 參考 文件。