简体   繁体   English

TypeScript + VSCode中的自定义模块分辨率

[英]Custom module resolution in TypeScript + VSCode

I have the following project structure: 我有以下项目结构:

<PROJECT_FOLDER>
├── node_modules
├── src
│   ├── components
│   │   └── MyAwesomeComponent.tsx
│   ├── views
│   │   └── MyAwesomeView
│   │       └── index.tsx
│   ├── Application.tsx
│   └── index.tsx
├── webpack.config.js
└── tsconfig.json

and the following tsconfig.json 和以下tsconfig.json

{
    "compilerOptions": {
        "outDir": "./dist/",
        "noImplicitAny": true,
        "moduleResolution": "classic",
        "module": "es6",
        "target": "es5",
        "jsx": "react",
        "allowJs": true,
        "sourceMap": true,
        "noImplicitReturns": true,
        "experimentalDecorators": true,

        "baseUrl": ".",
        "paths": {
            "*": [
                "src/*",
                "node_modules/*"
            ]
        },
    }
}

Assume I have react in node_modules (and even @types/react installed). 假设我在node_modules react了(甚至安装了@types/react )。 When I'm tryin to import somewhat, for example import * as React from "react" or import MyComponent from "components/MyAwesomeComponent , both imports are errorneous with message "Cannot find module..." and so on. 当我尝试导入时,例如import * as React from "react"import MyComponent from "components/MyAwesomeComponent import * as React from "react" import MyComponent from "components/MyAwesomeComponent ,这两种导入都与错误消息“ Cannot find module ...”有关 ,依此类推。

As I'm writing the import string, VSCode suggests me modules from node_modules , but doesn't suggest me folders from src/* . 当我编写导入字符串时,VSCode建议我使用node_modules模块,但是不建议我使用src/*文件夹。

Relative import still works, but this is the hell, you know. 相对导入仍然有效,但是这很糟糕。

I'm definitely new to TypeScript, but I'm doing things according to the "Module Resolution" TypeScript docs, and it doesn't work. 我绝对不是TypeScript的新手,但是我正在根据“ Module Resolution” TypeScript文档进行操作,并且它不起作用。

Highly appreciate any help here! 非常感谢您的任何帮助!


Update 更新

I have changed my moduleResolution to node and set the config shared by @Alserda (thank you for answer, but looks like I'm doing something wrong, because you config doesn't solve the problem). 我已经改变了我moduleResolutionnode并设置由@Alserda共享的配置(谢谢你的回答,但看起来像我做错了什么,因为你的配置不解决问题)。 Then I run suggested tsc --traceResolution . 然后我运行建议的tsc --traceResolution It resolved all my imports as well, VSCode now resolving the node_modules , but still doesn't resolve my components/MyAwesomeComponent : 它也解决了我所有的导入问题,VSCode现在解决了node_modules ,但是仍然不能解决我的components/MyAwesomeComponent 在此处输入图片说明


Update 2 更新2

Well, my webpack.config.js does already have corresponding modules 好吧,我的webpack.config.js已经有了相应的模块 在此处输入图片说明

But I don't think that the problem is here, I even did not run webpack-dev-server , and I believe that VSCode doesn't use the webpack.config.js information to configure the project :) 但是我不认为问题出在这里,我什至没有运行webpack-dev-server ,并且我相信VSCode不会使用webpack.config.js信息来配置项目:)


Update 3 更新3

Here is the output for the components/MyAwesomeComponent import: 这是components/MyAwesomeComponent导入的输出:

======== Resolving module 'components/MyAwesomeComponent' from '/home/username/path/to/project/src/Application.tsx'. ========
Explicitly specified module resolution kind: 'NodeJs'.
'baseUrl' option is set to '/home/username/path/to/project/src', using this value to resolve non-relative module name 'components/MyAwesomeComponent'.
Resolving module name 'components/MyAwesomeComponent' relative to base url '/home/username/path/to/project/src' - '/home/username/path/to/project/src/components/MyAwesomeComponent'.
Loading module as file / folder, candidate module location '/home/username/path/to/project/src/components/MyAwesomeComponent', target file type 'TypeScript'.
File '/home/username/path/to/project/src/components/MyAwesomeComponent.ts' does not exist.
File '/home/username/path/to/project/src/components/MyAwesomeComponent.tsx' exist - use it as a name resolution result.
======== Module name 'components/MyAwesomeComponent' was successfully resolved to '/home/username/path/to/project/src/components/MyAwesomeComponent.tsx'. ========

Final update 最终更新

VSCode did not enforce update project settings from my tsconfig.json even after Reload TypeScript project . 即使在Reload TypeScript project之后, tsconfig.json也不从我的tsconfig.json强制执行更新项目设置。 I just restarted it, and everything works fine now! 我刚刚重新启动它,现在一切正常! :) :)

Thanks everybody for your help! 谢谢大家的帮助!

You probably have to add this key: 您可能必须添加以下密钥:

...
"include": [
    "src/**/*"
],
...

The path key that you are using is mainly for making TypeScript understand that your imports 'will work' for your Webpack configuration. 您使用的path密钥主要用于使TypeScript了解您的导入对于Webpack配置将“起作用”。 Say you have an alias key in your Webpack configuration like: 假设您在Webpack配置中有一个alias密钥,例如:

alias: {
  core: resolve(__dirname, '../src/services/core'),

(and you have your context key on your src folder). (并且您的src文件夹中有context密钥)。

Then you should add a path key in your tsconfig like 然后您应该在tsconfig中添加path键,例如

    "paths": {
        "core/*": ["./services/core/*"],

(with your src folder as baseURL (将您的src文件夹作为baseURL

I'm always using the following configuration for TypeScript & React.js. 我一直对TypeScript和React.js使用以下配置。 This has been working great for me for multiple projects. 对于多个项目,这对我来说一直很好。

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es3",
        "moduleResolution": "node",
        "baseUrl": "src",
        "allowSyntheticDefaultImports": true,
        "noImplicitAny": true,
        "strict": false,
        "sourceMap": true,
        "outDir": "dist/",
        "jsx": "react",

        "allowJs": true,
        "declaration": false,
        "removeComments": true,
        "noLib": false,
        "preserveConstEnums": true,
        "suppressImplicitAnyIndexErrors": true,
        "types": [ "node" ],
        "lib": ["es6", "dom"]
    },
    "include": [
        "src/**/*"
    ]
}

And if you're using awesome-typescript-loader , I also include this: 而且,如果您使用的是awesome-typescript-loader ,那么我还将包括以下内容:

    "awesomeTypescriptLoaderOptions": {
        "useCache": true,
        "forceIsolatedModules": true
    }

Edit: 编辑:

I think this is a webpack related error. 我认为这是一个与webpack相关的错误。 Have you set your source I think the import error is related to Webpack. 您是否设置了source我认为导入错误与Webpack有关。 Try setting the following in your Webpack config: 尝试在Webpack配置中设置以下内容:

const path = require('path');
...
context: path.resolve(__dirname, './src'),
resolve: {
  modules: ['src', 'node_modules']
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Material-UI 在 TypeScript 模块解析期间未找到组件 - Material-UI components not found during TypeScript module resolution 如何在 React/TypeScript 应用程序中的模块方法上获取 VSCode 智能感知? - How to get VSCode intellisense on module methods in a React/TypeScript app? 尽管在package.json中设置了“ main”属性,Typescript模块解析仍失败 - Typescript module resolution fails despite “main” property set in package.json 不带扩展模块分辨率 - Module Resolution without Extension 在 Create React App 中为节点模块添加自定义 Typescript 类型声明 - Adding custom Typescript type declaration for a node module in Create React App ES2015 模块语法优于自定义 TypeScript 模块和命名空间@typescript-eslint/no-namespace - ES2015 module syntax is preferred over custom TypeScript modules and namespaces @typescript-eslint/no-namespace dockerized React应用中的VSCode + Typescript - VSCode + Typescript in dockerized React app 如何在 package.json 中为自定义本地 npm 模块设置 VScode 智能感知? - How to set VScode intellisense for custom local npm module in package.json? Webpack模块解决方案有问题 - Having trouble with the webpack module resolution 包裹打字稿模块扩充 - Parcel typescript module augmentation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM