别名源代码导入
有两种方法可以覆盖导入路径:
- 在
tsconfig.json
中使用paths
属性 - 在
package.json
中使用alias
属性
别名本地 TypeScript 导入
要为本地导入设置别名,请在 tsconfig.json
中使用 paths
映射:
{
"extends": "plasmo/templates/tsconfig.base",
"exclude": ["node_modules"],
"include": ["./**/*.ts", "./**/*.tsx"],
"compilerOptions": {
"paths": {
"~*": ["./src/*"],
"@Components/*": ["./src/components/*"]
},
"baseUrl": "."
}
}
然后可以这样使用:
import { Button } from "@Components/button"
import { Checkbox } from "@Components/checkbox"
import { Header } from "@Components/header"
import { Input } from "@Components/input"
参见示例:bug-244-alias-local-imports (opens in a new tab)
别名外部 TypeScript 模块
要为外部 TypeScript 模块设置别名,可以在 tsconfig.json
中使用指向外部目录的 paths
映射:
{
"extends": "plasmo/templates/tsconfig.base",
"exclude": ["node_modules"],
"include": ["./**/*.ts", "./**/*.tsx"],
"compilerOptions": {
"paths": {
"coolio/*": ["../../../some-cool-package/*"]
},
"baseUrl": "."
}
}
导入变为:
import { hello } from "coolio/hello"
别名外部导入
可以使用 alias
字段将导入路径映射到项目外部的文件:
{
"alias": {
"some-cool-identifier/hello": "../../../cool-file.js"
}
}
确保也在 TypeScript 声明文件 cool-file.d.ts
中声明该导入:
declare module "some-cool-identifier/hello" {
export const hello: string
}
并将该文件包含在 tsconfig.json
中:
{
...
"include": ["./**/*.ts", "./**/*.tsx", "./cool-file.d.ts"]
}
然后可以在代码中使用它:
import { hello } from "some-cool-identifier/hello"
别名 API 兼容模块
在 package.json
中使用 alias
字段为 API 兼容模块设置别名。可以映射到本地文件或依赖包。
使用 Preact 替代 React
由于 Preact 的 API 与 React 兼容,可以这样设置别名:
{
"alias": {
"react": "preact/compat",
"react-dom": "preact/compat"
}
}