无法从typescript项目的子目录中加载React组件

时间:2018-04-01 19:42:41

标签: typescript

我创建了一个名为" components"的目录。在src目录下,然后将我的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应用程序将完美运行。

1 个答案:

答案 0 :(得分:0)

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

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

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