[英]Set up import aliases in Gatsby / Typescript project
我尝试在我的 Gatsby 和 Typescript 项目中创建导入别名。 我使用 npm package eslint-import-resolver-alias 。
所以我可以使用:
import Layout from '@components/Layout';
在gatsby-node.js
我有:
常量路径 = 要求('路径');
exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
resolve: {
alias: {
@components: path.resolve(__dirname, 'src/components'),
@static: path.resolve(__dirname, 'static'),
},
},
});
};
在.eslintrc.js
我有:
alias: [['@components', './src/components']]
在我有:
"baseUrl": "./src",
"paths": {
"@components": ["/components"]
现在我在 VSCode 中得到这个错误:
无法解析模块“组件/布局”的路径。eslintimport/no-unresolved
您不需要gatsby-plugin-resolve-src
来允许从/src
导入。 默认情况下,它由 Gatsby 处理。 如果正确导出,它在项目文件夹中的所有内容都可以作为 React 组件导入。
如果你想在你的导入中添加别名,路径的多重相对性以避免类似的事情:
import Subscribe from '../../../../../../../core/modules/newsletter/mixins/Subscribe'
您可以通过添加setWebpackConfig
API (在您的gatsby-node.js
中:
exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
resolve: {
modules: [path.resolve(__dirname, `src`), `node_modules`],
},
});
};
此外,您可以添加:
const path = require("path");
exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
resolve: {
alias: {
"@components": path.resolve(__dirname, "src/components"),
"@static": path.resolve(__dirname, "static")
}
}
});
}
第一个片段将允许您从node_modules
和/components
文件夹中的第二个进行动态导入。
要解析 ESlint 导入,您需要通过以下方式安装eslint-import-resolver-alias
插件:
npm i -D eslint-import-resolver-alias
然后在.eslint
文件中添加以下配置:
{
"settings": {
"import/resolver": {
"alias": [
["@components", "./src/components"]
]
}
}
}
您可能会发现这篇文章很有帮助。
我通过在.eslintrc.js
中添加paths: ['./src'],
import/resolver
来实现它:
'import/resolver': {
node: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
paths: ['./src'],
},
alias: [['components', './src/components']],
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.