typescript Webpack resolve.alias 不适用于打字稿?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40443806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:27:05  来源:igfitidea点击:

Webpack resolve.alias does not work with typescript?

typescriptwebpack

提问by starcorn

I try to shorten my imports in typescript

我尝试在打字稿中缩短我的导入

from import {Hello} from "./components/Hello";

import {Hello} from "./components/Hello";

to import {Hello} from "Hello";

import {Hello} from "Hello";

For that I found out you can use resolve.aliasin webpack thus I configured that part as following

为此,我发现您可以resolve.alias在 webpack 中使用,因此我将该部分配置如下

resolve: {
    root: path.resolve(__dirname),
    alias: {
        Hello: "src/components/Hello"
    },
    extensions: ["", ".ts", ".tsx", ".js"]
},

Webpack builds, and the output bundle.js works. However typescript's intellisense complain it cannot find the module

Webpack 构建,并且输出 bundle.js 工作。然而打字稿的智能感知抱怨它cannot find the module

So my question is whether or not webpack's resolve.alias works with typescript?

所以我的问题是 webpack 的 resolve.alias 是否适用于打字稿?

I found following issuebut there's no answer to it.

我发现了以下问题,但没有答案。

回答by Daniel Rosenwasser

If you're using ts-loader, you might have to synchronize your webpack alias/resolvesettings with your pathssetting in your tsconfig.json.

如果你使用ts-loader,你可能需要您的WebPack同步alias/resolve设置请paths在您的设置tsconfig.json

{
    "compilerOptions": {
        "baseUrl": "./",
        "paths": {
            "Hello": ["src/components/Hello"]
        }
    }
}

If you're using awesome-typescript-loader, then webpack can figure this out automatically from the pathssetting in your tsconfig.json, as per the status on this issue from the repo. That way, you don't need to duplicate the same information in your Webpack aliasfield.

如果您正在使用awesome-typescript-loader,那么 webpack 可以根据 repo 中关于此问题的状态,从paths您的设置中自动tsconfig.json计算出这一点。这样,您就不需要在 Webpackalias字段中复制相同的信息。

回答by Caio Saldanha

Dudes, you are missing one very important point in tsconfig.json: The matching pattern!

伙计们,您在 tsconfig.json 中遗漏了一个非常重要的点:匹配模式!

It should be configured like this:

它应该像这样配置:

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

The "*" is the important part to tell TS to match anything on the right side.

“*”是告诉 TS 匹配右侧任何内容的重要部分。

I found that out from this article: https://medium.com/@martin_hotell/type-safe-es2015-module-import-path-aliasing-with-webpack-typescript-and-jest-fe461347e010

我从这篇文章中发现:https: //medium.com/@martin_hotell/type-safe-es2015-module-import-path-aliasing-with-webpack-typescript-and-jest-fe461347e010

回答by pixelbits

As others have mentioned, you need to provide an aliasin your webpack.config.js:

正如其他人提到的,您需要alias在 webpack.config.js 中提供一个:

    resolve: { 

        extensions: [".ts", ".js"],
        alias: {
            forms: path.resolve(__dirname, "src/forms/")
        } 
    },

This needs to be in synch with your tsconfig.jsonfile (baseUrl and paths are required).

这需要与您的tsconfig.json文件同步(需要 baseUrl 和路径)。

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

Note: The wildcard pattern is necessary to match with your resolve alias configuration.

注意:通配符模式是与您的解析别名配置匹配所必需的。

Then you can import any library using your alias:

然后你可以使用你的别名导入任何库:

import { FormsModule } from "forms/my-forms/my-forms.module";

回答by Patrick Stival Chaerke

If anyone still have this issue, don't forget to add your folder to the "include" option on tsconfig.json like this:

如果有人仍然遇到此问题,请不要忘记将您的文件夹添加到 tsconfig.json 上的“include”选项,如下所示:

{
  "compilerOptions": {
    "sourceMap": true,
    "allowJs": true,
    "baseUrl": "./",
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node",
    "lib": [
      "es2016",
      "dom"
    ]
  },
  "outDir": "./built/",
  "include": [
    "./src/**/*",
    "./tests/**/*"
  ]
}

回答by AMilassin

I had to make a small adjustment to Caio Saldanha's solution to make it work in my environment.

我不得不对 Caio Saldanha 的解决方案进行小幅调整,使其适用于我的环境。

I am using Babel 7 with babel-plugin-module-resolverto resolve aliases. No ts-loaderor awesome-typescript-loaderas Babel 7 supports TypeScript out of the box using @babel/preset-typescript. I had to add an extra path configuration for each alias to load the module root (e.g. index.ts) automagically:

我正在使用 Babel 7 withbabel-plugin-module-resolver来解析别名。不支持ts-loaderawesome-typescript-loader因为 Babel 7 使用@babel/preset-typescript. 我必须为每个别名添加额外的路径配置以index.ts自动加载模块根目录(例如):

"baseUrl": ".",
"paths": {  // this must be synchronized with .babelrc.js's module-resolver alias config
    "component": ["src/component/index.ts"],
    "component/*": ["src/component/*"],
    ...
}

Having an index.tsin the /componentfolder with the following content:

具有index.ts/component包含以下内容的文件夹:

export { default as Logo } from './Logo';

Without the extra .../index.tsline this import didn't work for me:

如果没有额外的.../index.ts行,这个导入对我不起作用:

import { Logo } from 'component';  

Alias config in .babelrc.js:

别名配置.babelrc.js

plugins: [
[
    'module-resolver',
    {
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
        root: ['./src'],
        alias: {
        // this must be synchronized with tsconfig.json's path configuration
            component: './src/component',
        },
    },
],

回答by Yash Agrawal

There are 2 cases

有2种情况

  1. When you write custom webpackIt works with typescript but not directly. To explain, there are 2 types of compilation happening in backstage. First tsx -> js for which tsconfig.json plays the role, but when you actually compile the js code then webpack comes into picture. So for aliases, resolve should be placed at both places i.e in tsconfig and webpack to successfully run the application
  2. when you use default(after create react app): You just need to add "baseUrl": "./src"in tsconfig and see the code work.
  1. 当您编写自定义 webpack 时,它可以与typescript一起使用,但不能直接使用。解释一下,有两种类型的编译发生在后台。首先是 tsx -> js,其中 tsconfig.json 发挥作用,但是当您实际编译 js 代码时,webpack 就会出现。所以对于别名,resolve 应该放在两个地方,即在 tsconfig 和 webpack 中才能成功运行应用程序
  2. 当您使用默认值时(在创建反应应用程序之后):您只需要添加"baseUrl": "./src"tsconfig 并查看代码工作。

回答by Dimitris Karagiannis

I thinkyou can do this and have it work the way you describe:

认为你可以做到这一点,并让它按照你描述的方式工作:

resolve: {
    root: [
        path.resolve(__dirname),
        <path_to_components_directory> //e.g. path.resolve(__dirname, 'src', 'components')
    ], 
    extensions: ["", ".ts", ".tsx", ".js"]
},

Then you can do import {Hello} from "Hello";

然后你可以做 import {Hello} from "Hello";

I know I do this to resolve file paths in my src/jsdirectory. I am not using typescript though, but I don't think it would affect the result.

我知道我这样做是为了解析src/js目录中的文件路径。虽然我没有使用打字稿,但我认为它不会影响结果。