我正在尝试使用typescript路径映射来改进我的导入。
目前我有以下源结构
tsconfig.json
src
..index.ts
..moduleA
....index.ts
所以,在我的tsconfig.json里面
"baseUrl": ".",
"paths": {
"moduleA": ["./src/moduleA/index.ts"]
},
并在src \ index.js上我打电话
import { MyClassFromModule} from 'moduleA';
所有东西都编译井,但当React Native尝试加载模块时,我收到以下错误:
error: bundling: UnableToResolveError: Unable to resolve module `mymodule` from `C:\Git\phoenix\modules-poc\native\build\index.android.js`: Module does not exist in the module map or in these directories: C:\Git\phoenix\modules-poc\native\node_modules
所以事情是模块不在node_modules里面,而是在源文件夹里面。如何告诉React Native从src文件夹加载模块?
谢谢
react-native-typescript-transformer只是将ts转换为js。所有导入仍然在编译阶段使用metro bundler处理到一个捆绑文件,因此您也需要对其进行配置。尝试使用这样的.babelrc的babel插件模块解析器
{
"presets": ["react-native"],
"plugins": [
["module-resolver", {
"root": ["./src"],
"extensions": [".js", ".ts", ".tsx", ".ios.js", ".android.js"]
}]
]
}
react-native-typescript-transformer的现代替代品是babel 7的打字稿预设。如果项目中没有流类型,则可以使用它。检查这个存根项目https://github.com/Microsoft/TypeScript-Babel-Starter仍然应该配置.babelrc,但现在它更明显。