使用路径别名导入源代码
Plasmo 框架支持两种方式来配置导入路径别名:
- 在
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
为外部 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"
}
}最后更新于