如何让 tsconfig 在将文件、别名导入组件时识别".graphql"文件、别名?



所以,我包含了一些"graphql"文件到我的组件,他们给我TS错误,因为导入路径无法识别。这一切都工作,只是给出TS错误。

import QUERY_GET_CATS from "@gql/GetCats.graphql";

错误:TS2307:找不到模块@gql/GetCat。或其相应的类型声明

这是我的tsconfig:

{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"*": [
"./*"
],
"@gql/*": [
"./api/gql/*"
]
},
"lib": ["dom", "dom.iterable", "esnext"],
"strict": true,
"noUnusedLocals": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"isolatedModules": true,
"jsx": "preserve",
"downlevelIteration": true,
"allowJs": true,
"skipLibCheck": true,
"resolveJsonModule": true
},
"exclude": [
"cypress",
"coverage",
"node_modules",
"build",
"dist",
"out",
".next",
"next.config.js",
"./**/*.js",
"./**/*.jsx",
"./**/*.scss"
],
"include": [
"next-env.d.ts",
"./**/*.ts",
"./**/*.tsx"
]
}

我eslintrc

const path = require('path');
module.exports = {
parserOptions: {
ecmaVersion: 2019,
sourceType: 'module',
project: './tsconfig.json',
ecmaFeatures: {
jsx: true,
},
},
parser: '@typescript-eslint/parser',
extends: [
'eslint:recommended',
'plugin:react-hooks/recommended',
'plugin:react/recommended',
'airbnb-typescript',
'prettier',
'prettier/react',
'eslint-config-prettier',
'eslint-config-prettier/@typescript-eslint',
'plugin:cypress/recommended'
],
globals: {
cy: true
},
rules: {
strict: ['error', 'never'],
'import/no-cycle': 0,
'import/prefer-default-export': 0,
'global-require': 0,
'react/jsx-key': 1,
'prefer-destructuring': 1,
"import/no-extraneous-dependencies": 1,
'no-console': 'warn',
'no-param-reassign': [
2,
{
props: false,
},
],
'react/prop-types': 0,
'camelcase': ['warn', {ignoreDestructuring: true, properties: 'never'}],
'react/no-unescaped-entities': 0,
'import/extensions': 'off',
'react/jsx-props-no-spreading': ['warn', {custom: 'ignore'}],
'jsx-a11y/click-events-have-key-events': 0,
'jsx-a11y/no-static-element-interactions': 0,
},
env: {
browser: true,
jest: true,
es2020: true,
'cypress/globals': true,
},
plugins: ['eslint-plugin-cypress'],
overrides: [
{
settings: {
'import/resolver': {
jest: {
jestConfigFile: path.join(__dirname, '/jest.config.js'),
},
},
},
},
],
};

注意:当我添加"./**/*.graphql"到"包括"。数组,没有帮助。注意我的其他别名都有用。只是不是"图形"的人。

因为这些文件是gql语法,而不是Typescript词典的一部分,所以你需要将它们定义为环境模块在typescript文档中描述的类型定义文件中。

documentNode.d.ts

declare module '*.graphql' {
import {DocumentNode} from 'graphql';
const value: DocumentNode;
export = value;
}

您还需要将"./**/*.graphql"添加到tsconfig的include部分。

应该注意的是,这基本上是一个虚拟/占位符,它允许您导入代码库中的文件,但不会从内容中派生任何类型信息。有一个来自graphql代码生成器的包叫做TypedDocumentNode,它可以让你把完全类型的documentnode拉到你的项目中,但我还没有尝试过,所以YMMV.

最新更新