您希望配置哪个导入别名?
我正在使用 Next.js 构建我的个人网站,运行以下命令后遇到了这个问题yarn create next-app --typescript:
? What import alias would you like configured? › @/*
我熟悉导入别名的概念,但我不知道 Next 希望如何回答这个问题。通常,我会使用多个导入别名,例如 `import a`、`import b` @styles、@components` import @hooksc` 等。
于是我决定做个实验。我@components在提示框里输入了内容,然后得到了这样的回复:
› Import alias must follow the pattern <prefix>/*
明白了。于是我试了一下@components/*,我的应用就创建好了。我检查了我的tsconfig.json(或jsconfig.json),并将其与使用默认设置的应用进行了比较@/*。
// tsconfig.json with default (@/*)
{
"compilerOptions": {
...
"baseUrl": ".",
"paths": {
"@/*": ["./*"]
}
},
...
}
// tsconfig.json with test (@components/*)
{
"compilerOptions": {
...
"baseUrl": ".",
"paths": {
"@components/*": ["./*"]
}
},
...
}
测试结果并非我所愿。过去,我曾使用过类似的模式:
// tsconfig.json
{
"compilerOptions": {
...
"baseUrl": ".",
"paths": {
"@components/*": ["components/*"],
"@styles/*": ["styles/*"],
"@hooks/*": ["hooks/*"]
}
},
...
}
这使我可以像这样引用导入项:
import Button from '@components/Button';
使用 Next.js 设置向导提供的默认值 ( "@/*": ["./*"]) 可以让我实现同样的功能,而无需显式地设置每个路径——我只需要在我的导入路径后tsconfig.json添加一个额外的 ( ) ,如下所示:/@
import Button from '@/components/Button';
这样可以避免我tsconfig.json感到腹胀,而且更容易保持身材(相比我以前用的那种方法)。太棒了!
我能想到的唯一需要修改此默认设置的情况是,如果您正在使用src/文件夹。
您还有其他我没想到的应用场景吗?如果有,请留言!
文章来源:https://dev.to/justindwyer6/what-import-alias-would-you-like-configured-51n4
