【问题标题】:React Native with typescript unable to resolve modulesReact Native 与 typescript 无法解析模块
【发布时间】:2020-04-29 03:21:00
【问题描述】:

这很尴尬,但我不知道还能做什么。我想将我的小型 React Native 项目移植到 TypeScript,所以我使用 TypeScript 模板创建了一个空的 React Native 项目,调整了 tsconfig.json 以使用自定义路径,例如 @app,然后我尝试运行它。它没有。这是昨天,我做了一些谷歌搜索,但是那些有同样问题的人建议清理打包器,删除node_modules并重新安装包,例如this one,所以我做了,但它没有用.

这些是我重新安装react-native-cli 的步骤(起初我以为问题出在过时的软件包上,其实不是):

  • npm uninstall -g react-native-cli
  • yarn global add @react-native-community/cli

下面的那些我已经关注了很多次了,我不记得确切的数字了:

  • npx react-native init MyApp --template react-native-template-typescript
  • yarn add redux redux-logger redux-thunk react-redux
  • yarn add --dev @types/react @types/react-redux @types/redux-logger

然后对tsconfig.json 进行更改,所以看起来像这样(我的更改标记为->):

{
  "compilerOptions": {
    /* Basic Options */
    "target": "esnext",                       /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
    "module": "esnext",                       /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "lib": ["dom", "esnext"],                 /* Specify library files to be included in the compilation. */
    "allowJs": true,                          /* Allow javascript files to be compiled. */
    "jsx": "react-native",                    /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    "noEmit": true,                           /* Do not emit outputs. */
    "incremental": true,                      /* Enable incremental compilation */
    "isolatedModules": true,                  /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */

    /* Module Resolution Options */
    "moduleResolution": "node",               /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
->  "baseUrl": "./src",                       /* Base directory to resolve non-absolute module names. */
->  "paths": {                                /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
->    "@app/*": ["./*"]
->  },
    "allowSyntheticDefaultImports": true,     /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */    
  },
  "exclude": [
    "node_modules", "babel.config.js", "metro.config.js", "jest.config.js"
  ]
}

我的项目结构如下:

MyApp
├── ios
├── android
├── src
│   ├── index.tsx
│   ├── constants
│   │   └── app.json
│   ├── support   
│   │   └── store.tsx   
│   └── reducers   
│       └── index.tsx
├── tsconfig.json
├── package.json
├── index.js 
└── [ the rest ]

当我尝试在MyApp/src/index.tsx 中输入import {initStore} from '@app/support/store' 时,Metro 会给我以下信息:

Loading dependency graph, done.
error: bundling failed: Error: Unable to resolve module `@app/support/store` from `src/index.tsx`: @app/support/store could not be found within the project.

然后我尝试使用以下命令进行清理,但它也没有任何好处:

  • watchman watch-del-all && rm -rf $TMPDIR/react-* && rm -rf node_modules/ && npm cache verify && npm install && npm start -- --reset-cache

但是,有趣的是,在那之后我调整了tsconfig.json,Atom 不会抱怨像@app/support/store 这样的路径,它甚至提供了自动补全功能,它将@app/support/ 识别为目录,将@app/support/store 识别为脚本,所以我假设tsconfig.json 不是问题。

【问题讨论】:

  • 1.我假设您重新启动了打包程序? 2. 这就是你得到的所有错误吗? 3. import 是否适用于support/store 之外的任何其他内容,例如@app/constants/app?
  • @nabn 不,导入不适用于任何具有绝对路径的文件。打包机是指Metro?然后重新启动它不会修复它,我试过了,以及清除缓存yarn start --reset-cache

标签: typescript react-native


【解决方案1】:

似乎问题出在 babel 配置上。你需要运行

yarn add --dev babel-plugin-module-resolver

安装模块解析器,然后调整babel.config.js,使其看起来像这样:

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      'module-resolver',
      {
        root: ['./src'],
        alias: {
          '^@app/(.+)': './src/\\1',
        },
      },
    ],
  ],
}

【讨论】:

  • 这有帮助,谢谢!确保在将模块解析器添加到 babel 配置后删除守望者缓存。
  • @Katherine 包名应该是babel-plugin-module-resolver
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-11
  • 2016-03-23
  • 1970-01-01
  • 2018-11-18
  • 1970-01-01
  • 2020-04-15
  • 2020-03-02
相关资源
最近更新 更多