运行 tsc 时,TypeScript 出现错误 TS2307 找不到模块“src/”

问题描述 投票:0回答:1

我正在尝试为我的 React Native 项目中的包配置 tsconfig.json 以添加模块解析并使代码更清晰,而不是

import { LABELS } from "../../../constants";

我可以写

import { LABELS } from "src/constants"; or import { LABELS } from "@app-content/constants";

这是我的 tsconfig.json

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "@app-content/*": ["./src/*"]
        }
    },
    "include": ["__tests__/**/*", "src/**/*", "typings/*"]
}

所以文件夹结构是这样的:

root
--src
--packages
---src
----components
----constants
---tsconfig.json

如果我写“src/”或“@app-content/”,该分辨率在 vs-code 上可以正常工作,它会显示正确的文件夹,并且当时没有错误,应用程序也运行成功,但是当我运行命令

tsc
它给出错误

error TS2307: Cannot find module 'src/constants' or its corresponding type declarations.
javascript node.js typescript react-native tsconfig
1个回答
0
投票

该问题可能是因为您需要调整一些额外的编译器选项并确保路径配置正确。 这是更正后的

tsconfig.json
配置:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@app-content/*": ["./src/*"],
      "src/*": ["./src/*"]
    },
    "module": "commonjs",
    "target": "es6",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true,
    "outDir": "./dist"
  },
  "include": ["__tests__/**/*", "src/**/*", "typings/*"],
  "exclude": ["node_modules", "dist"]
}

此外,您可能需要配置构建工具:

如果您正在使用

Metro
,请将其添加到您的
metro.config.js

const { getDefaultConfig } = require('metro-config');

module.exports = (async () => {
  const {
    resolver: { sourceExts, assetExts }
  } = await getDefaultConfig();
  
  return {
    transformer: {
      babelTransformerPath: require.resolve('react-native-typescript-transformer')
    },
    resolver: {
      sourceExts: [...sourceExts, 'tsx', 'ts'],
      extraNodeModules: {
        '@app-content': __dirname + '/src',
        'src': __dirname + '/src'
      }
    }
  };
})();

如果您在进行这些更改后仍然收到错误消息,请尝试:

  1. 删除
    node_modules/.cache
    文件夹
  2. 如果您有这些脚本,请运行
    yarn clean
    npm run clean
  3. 重新启动您的开发服务器
  4. 再次运行
    tsc
© www.soinside.com 2019 - 2024. All rights reserved.