【问题标题】:Not able to load React Components from a subdirectory in a typescript project无法从打字稿项目中的子目录加载 React 组件
【发布时间】:2018-09-11 02:55:47
【问题描述】:

我在 src 目录下创建了一个名为“components”的目录,然后将我的 React 组件作为 App.tsx 移动到该目录中

我将 tsconfig.json 修改为

{
   "compilerOptions": {
      "allowSyntheticDefaultImports": true,
      "jsx": "react",
      "module": "commonjs",
      "noImplicitAny": true,
      "outDir": "./build/",
      "baseUrl": "./src",
      "preserveConstEnums": true,
      "removeComments": true,
      "sourceMap": true,
      "target": "es5",
      "paths": {
         "~/*": ["./*"]
      }
   },
   "include": [
      "./src/**/*"
   ],
   "exclude": [
      "node_modules",
      "**/*.spec.ts"
   ]
}

在 webpack.config.js 的末尾我添加了这一行

resolve: {
  extensions: ["js", "ts", "tsx", "*"] 
}

现在在我的 index.tsx 中

import { App } from './components/App'

但是当我执行nom start 时,我得到一个错误

ERROR in ./src/index.tsx
Module not found: Error: Can't resolve './components/App' in '/Users/user1/IdeaProjects/react-ts-todo/src'
 @ ./src/index.tsx 5:12-39
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.tsx

ERROR in ./node_modules/querystring-es3/index.js
Module not found: Error: Can't resolve './decode' in '/Users/user1/IdeaProjects/react-ts-todo/node_modules/querystring-es3'
 @ ./node_modules/querystring-es3/index.js 3:33-52
 @ ./node_modules/url/url.js
 @ (webpack)-dev-server/client?http://localhost:8080
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.tsx

我已签入我的代码 here,以防万一您需要查看示例应用程序。

如果我在 index.tsx 中包含所有内容,我的 React 应用程序就可以完美运行。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    没关系。我自己解决了 webpack.config.js 条目应该是

    resolve: {
      extensions: [".js", ".ts", ".tsx"] 
    }
    

    我错过了“。”在扩展名之前。

    【讨论】:

      猜你喜欢
      • 2019-10-22
      • 2017-11-14
      • 2021-05-17
      • 2021-09-01
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      相关资源
      最近更新 更多