Skip to main content

导入组件

多亏 webpack,此项目设置支持 ES6 模块。

¥This project setup supports ES6 modules thanks to webpack.

虽然你仍然可以使用 require()module.exports,但我们建议你改用 importexport

¥While you can still use require() and module.exports, we encourage you to use import and export instead.

例如:

¥For example:

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;

注意 默认导出和命名导出之间的区别。这是错误的常见来源。

¥Be aware of the difference between default and named exports. It is a common source of mistakes.

我们建议你在模块仅导出单个东西(例如,组件)时坚持使用默认导入和导出。这就是你使用 export default Buttonimport Button from './Button' 时得到的结果。

¥We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use export default Button and import Button from './Button'.

命名导出对于导出多个函数的实用程序模块很有用。一个模块最多可以有一个默认导出和任意多个命名导出。

¥Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like.

了解有关 ES6 模块的更多信息:

¥Learn more about ES6 modules:

绝对导入

¥Absolute Imports

你可以配置你的应用以支持使用绝对路径导入模块。这可以通过在项目的根目录中配置 jsconfig.jsontsconfig.json 文件来完成。如果你在项目中使用 TypeScript,你将已经有一个 tsconfig.json 文件。

¥You can configure your application to support importing modules using absolute paths. This can be done by configuring a jsconfig.json or tsconfig.json file in the root of your project. If you're using TypeScript in your project, you will already have a tsconfig.json file.

下面是一个 JavaScript 项目的示例 jsconfig.json 文件。如果文件不存在,你可以创建该文件:

¥Below is an example jsconfig.json file for a JavaScript project. You can create the file if it doesn't already exist:

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

如果你使用的是 TypeScript,则可以在项目的 tsconfig.json 文件的 compilerOptions 中配置 baseUrl 设置。

¥If you're using TypeScript, you can configure the baseUrl setting inside the compilerOptions of your project's tsconfig.json file.

现在你已经将项目配置为支持绝对导入,如果你想导入位于 src/components/Button.js 的模块,你可以像这样导入模块:

¥Now that you've configured your project to support absolute imports, if you want to import a module located at src/components/Button.js, you can import the module like so:

import Button from 'components/Button';

有关这些配置文件的更多信息,请参阅 jsconfig.json 参考tsconfig.json 参考 文档。

¥For more information on these configuration files, see the jsconfig.json reference and tsconfig.json reference documentation.