Skip to main content

绝对导入和模块路径别名

Examples

Next.js 内置支持 tsconfig.jsonjsconfig.json 文件的 "paths""baseUrl" 选项。

¥Next.js has in-built support for the "paths" and "baseUrl" options of tsconfig.json and jsconfig.json files.

这些选项允许你将项目目录别名为绝对路径,从而更轻松地导入模块。例如:

¥These options allow you to alias project directories to absolute paths, making it easier to import modules. For example:

// before
import { Button } from '../../../components/button'

// after
import { Button } from '@/components/button'

很高兴知道:create-next-app 将提示你配置这些选项。

¥Good to know: create-next-app will prompt to configure these options for you.

绝对导入

¥Absolute Imports

baseUrl 配置选项允许你直接从项目的根目录导入。

¥The baseUrl configuration option allows you to import directly from the root of the project.

此配置的示例:

¥An example of this configuration:

{
"compilerOptions": {
"baseUrl": "."
}
}
export default function Button() {
return <button>Click me</button>
}
export default function Button() {
return <button>Click me</button>
}
import Button from 'components/button'

export default function HomePage() {
return (
<>
<h1>Hello World</h1>
<Button />
</>
)
}
import Button from 'components/button'

export default function HomePage() {
return (
<>
<h1>Hello World</h1>
<Button />
</>
)
}

模块别名

¥Module Aliases

除了配置 baseUrl 路径之外,你还可以使用 "paths" 选项来配置 "alias" 模块路径。

¥In addition to configuring the baseUrl path, you can use the "paths" option to "alias" module paths.

例如,以下配置将 @/components/* 映射到 components/*

¥For example, the following configuration maps @/components/* to components/*:

{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/components/*": ["components/*"]
}
}
}
export default function Button() {
return <button>Click me</button>
}
export default function Button() {
return <button>Click me</button>
}
import Button from '@/components/button'

export default function HomePage() {
return (
<>
<h1>Hello World</h1>
<Button />
</>
)
}
import Button from '@/components/button'

export default function HomePage() {
return (
<>
<h1>Hello World</h1>
<Button />
</>
)
}

每个 "paths" 都相对于 baseUrl 位置。例如:

¥Each of the "paths" are relative to the baseUrl location. For example:

// tsconfig.json or jsconfig.json
{
"compilerOptions": {
"baseUrl": "src/",
"paths": {
"@/styles/*": ["styles/*"],
"@/components/*": ["components/*"]
}
}
}
// pages/index.js
import Button from '@/components/button'
import '@/styles/styles.css'
import Helper from 'utils/helper'

export default function HomePage() {
return (
<Helper>
<h1>Hello World</h1>
<Button />
</Helper>
)
}