我正在尝试为我的 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.
该问题可能是因为您需要调整一些额外的编译器选项并确保路径配置正确。 这是更正后的
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'
}
}
};
})();
如果您在进行这些更改后仍然收到错误消息,请尝试:
node_modules/.cache
文件夹yarn clean
或 npm run clean
tsc