为什么在将一个typescript文件导入到另一个typescript文件时绝对路径不起作用,而在其他方面却可以?

eqfvzcg8  于 2022-12-05  发布在  TypeScript
关注(0)|答案(1)|浏览(370)

bounty明天到期。回答此问题可获得+50声望奖励。gabriellend希望吸引更多注意力此问题:你好!这是一个我一直无法解开的谜题,似乎是随机的,谢谢!

第二次编辑:当我试图在函数中引用Types时,它就中断了,并需要相对导入(以前,它只作为参数引用,这很好)。我已经尝试了很多解决绝对路径问题的方法。考虑以下问题的主要症结:绝对路径适用于导入ts文件的js文件、导入js文件的js文件和导入js文件的ts文件, 但不适用于导入ts文件的ts文件 。这似乎是我的tsconfig的一个问题,但据我所知它看起来是正确的。
第一次编辑:新的光线已经在下面。认为这部分的主要症结问题,其余的背景材料。我正在转换一个现有的React原生项目到Typescript。我正在导入两个ts文件到另一个ts文件。一个工作,一个不工作。
作品:import * as Types from 'app/lib/api/interfaces'
不起作用:import * as API from 'app/lib/api/index'
唯一的区别是Types只包含接口和类型,而API包含调用我的后端的函数。为什么一个可以工作而另一个不行呢?(相对导入确实可以工作)
我正在将一个现有的React Native项目转换为Typescript。我能够将一个ts文件导入到一个js文件中,如下所示(我读到,在执行此操作时必须明确,没有扩展名就不起作用):

import * as API from 'app/lib/api/index.ts'

当我将js文件转换为ts进行导入时,我得到了这个打字错误,但应用程序仍然构建:
导入路径不能以."ts“扩展名结尾。
当我从导入中删除扩展时(我是如何进行所有导入的):

import * as API from 'app/lib/api/index'

打字错误消失了,但应用程序未能建立,我得到了臭名昭著的:
在项目或以下目录中找不到app/lib/api/index:节点模块等。
我花了很多时间阅读文章,Stack,用我的配置文件尝试不同的配置(见下面示例中注解掉的代码),没有任何工作,直到我偶然发现:
代替:

import * as API from 'app/lib/api/index';

何月道:

import type * as API from 'app/lib/api/index';

而且它构建得很好,没有错误,所有功能似乎都能正常工作!但是,现在我又遇到了一个打字错误:
“API”不能用作值,因为它是使用“import type”导入的。
所以,这是不对的。我想我需要重新开始。
使用相对导入可以工作,但这是丑陋的,非相对/绝对导入在其他任何地方都可以工作,所以我想避免这种情况:
x1米20英寸
提前感谢大家的帮助!
以前的事我试过:

  • 清除守卫和地铁缓存。
  • tsconfig.json中设置paths,在.babelrc中设置alias(请参见下文)。
  • 从路径中删除indeximport * as API from 'app/lib/api
  • 使用js文件扩展名:x1米28英寸1x
  • 重新安装node_modulespods,重新启动TS服务器、VSCode和我的计算机。
  • 将以下内容以不同的组合添加到我的.eslintrc.js中:

第一个
settingsrules节点中尝试了不同的组合:

'import/extensions': 0
'import/resolver': {
      'babel-module': {
        "extensions": [".js", ".jsx", ".ts", ".tsx"],
        "alias": {
          "app/*": "./app/*"
        }
      },
      node: {
        paths: ["."]
        extensions: [".js", ".jsx", ".ts", ".tsx"],
        moduleDirectory: ['node_modules', '.'],
      }
    }

除了这个以外,非相对导入也在工作,所以我不认为它与tsconfig有任何关系。我的直觉告诉我这个问题可能是与我的eslint配置有关,或者可能是我的metro.config.js,但当然我可能是错的!
.eslintrc.js

module.exports = {
        env: {
        browser: true,
        es6: true,
      },
      // resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] },
      extends: [
        'plugin:react/recommended',
        'airbnb',
        'airbnb-typescript',
        // 'plugin:import/typescript',
      ],
      globals: {
        Atomics: 'readonly',
        SharedArrayBuffer: 'readonly',
      },
      parser: '@typescript-eslint/parser',
      parserOptions: {
        ecmaFeatures: {
          jsx: true,
        },
        ecmaVersion: 2020,
        sourceType: 'module',
        project: `./tsconfig.json`,
      },
      plugins: [
        'react',
        'import',
        // '@typescript-eslint'
      ],
      rules: {
        'react/no-did-update-set-state': 'off',
        'react/prop-types': 'off',
        // 'import/resolver': { 
        //    "node": {
        //      "extensions": [".js", ".jsx", ".ts", ".tsx"],
        //      moduleDirectory: ['node_modules', '.'],
        //    },
        // }
        // 'import/extensions': 0 
      },
      settings: {
        'import/resolver': { 
          'babel-module': {
            //"extensions": [".js", ".jsx", ".ts", ".tsx"],
            //"alias": {
            //"app/lib/api/index": "./app/lib/api/index.ts"
            }
          },
          // typescript: {},
          // node: {
          //   extensions: [".js", ".jsx", ".ts", ".tsx"],
          //   moduleDirectory: ['node_modules', '.'],
          // }, 
        }
        // 'import/extensions': 0
      },
    };

metro.config.js

module.exports = {
      resolver: {
        sourceExts: ['jsx', 'js', 'ts', 'tsx'],
      },
      transformer: {
        getTransformOptions: async () => ({
          transform: {
            experimentalImportSupport: false,
            inlineRequires: true,
          },
        }),
      },
    };

另外:
.babelrc

{
      "presets": ["module:metro-react-native-babel-preset"],
      "plugins": [
        ["module-resolver", {
          "root": ["."]
          // "alias": {
          //   "app/*": "app/*" (Also tried "./app/*")
          // }
        }]
      ]
    }

tsconfig.json

{
      "compilerOptions": {
        /* Visit https://aka.ms/tsconfig to read more about this file */

        /* Projects */
        // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
        // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
        // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
        // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
        // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
        // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

        /* Language and Environment */
        "target": "esnext",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
        "lib": ["es2017"],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
        "jsx": "react-native",                                /* Specify what JSX code is generated. */
        // "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
        // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
        // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
        // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
        // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
        // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
        // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
        // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
        // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */

        /* Modules */
        // "module": "commonjs",                                /* Specify what module code is generated. */
        // "rootDir": ".",                                  /* Specify the root folder within your source files. */
        "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
        "baseUrl": ".",                                  /* Specify the base directory to resolve non-relative module names. */
        // "paths": {
        //  "app/*": ["app/*"]
        // },                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
        // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
        // "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */
        "types": ["react-native", "jest"],                                      /* Specify type package names to be included without being referenced in a source file. */
        // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
        // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
        // "resolveJsonModule": true,                        /* Enable importing .json files. */
        // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

        /* JavaScript Support */
        "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
        // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
        // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

        /* Emit */
        // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
        // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
        // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
        // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
        // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
        // "outDir": "tsbuild",                                   /* Specify an output folder for all emitted files. */
        // "removeComments": true,                           /* Disable emitting comments. */
        "noEmit": true,                                   /* Disable emitting files from a compilation. */
        // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
        // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */
        // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
        // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
        // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
        // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
        // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
        // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
        // "newLine": "crlf",                                /* Set the newline character for emitting files. */
        // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
        // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
        // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
        // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
        // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
        // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

        /* Interop Constraints */
        "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
        "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
        "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
        // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
          "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

        /* Type Checking */
        "strict": true,                                      /* Enable all strict type-checking options. */
        // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */
        // "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */
        // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
        // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
        // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
        // "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
        // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
        // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
        // "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */
        // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */
        // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
        // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
        // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
        // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
        // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
        // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
        // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
        // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */

        /* Completeness */
        // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
        // "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
      },
      "exclude": [
        "node_modules",
        ".babelrc",
        "metro.config.js",
        "jest.config.js"
      ]
    }
mwngjboj

mwngjboj1#

将一个TypeScript文件导入另一个TypeScript文件时,绝对路径不起作用,因为TypeScript使用模块解析策略来确定如何定位和加载模块。此策略与Node.js解析模块的方式类似,并且基于“模块路径”的概念。
使用绝对路径导入TypeScript文件时,模块路径由文件系统上的文件位置确定。移动或重命名文件时,这可能会导致问题,因为模块路径将不再有效。此外,模块路径在不同计算机或不同环境中可能不同,这可能会导致不一致和错误。
为了避免这些问题,TypeScript建议在将一个TypeScript文件导入另一个TypeScript文件时使用相对路径。相对路径基于文件在文件系统上的相对位置,并且不受文件名或位置更改的影响。这使得相对路径比绝对路径更灵活和可靠。
例如,不使用绝对路径,如下所示:

import { SomeClass } from '/path/to/some/file';

您可以使用如下所示的相对路径:

import { SomeClass } from '../some/file';

这将使导入更可靠且更易于维护,并有助于避免在使用多个TypeScript文件时出现错误和不一致。

相关问题