tsconfig路径无法正常工作

时间:2018-06-04 10:58:54

标签: typescript alias tsconfig typescript2.9

我试图做一些与文档中的jquery path example非常相似的内容,但TS不断抛出TS2307(webpack编译正常):

"compilerOptions": {
    "baseUrl": "./src",
    "paths": {
        "@client": [
            "client",
        ],
        "@suir": [
            "../node_modules/semantic-ui-react/dist/commonjs", // not working
        ],
    },
    // …
},
"include": [
    "*.d.ts",
    "client/**/*",
    "../node_modules/semantic-ui-react", // is this necessary?
],

baseUrl更改为"."并更新includespaths没有任何区别(@client继续有效且@suir继续无效)。

"@suir"更改为"@suir/""@suir/*"(并将/*附加到其值)也没有任何区别。

我这样做的原因是为了简化我的导入(我明确指定它们而不是从捆绑中提取命名导出以减少我的供应商包大小 - 节省大约1 MB):< / p>

import Button from 'semantic-ui-react/dist/commonjs/elements/Button'; // works

import Button from '@suir/elements/Button'; // not found

9 个答案:

答案 0 :(得分:13)

正如 Emily Zhai 在评论中提到的,这有时只需要重新启动语言服务器。

在 VSCode 中,您可以按 Cmd/Ctrl + Shift + P 并搜索 Typescript: Restart TS Server

重新启动后,一切都开始为我工作。

答案 1 :(得分:6)

我也遇到了 .tsconfig 无法识别我的别名的问题(而在另一个应该有保存配置的项目中,它运行良好)。

事实证明,这是一个新手错误:我将 paths 属性放在 JSON 对象的末尾,但它必须是 compilerOptions 部分的嵌套属性:

// This does't work ❌
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
     //...
    "baseUrl": ".",
  },
  "include": ["next-env.d.ts", "twin.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"],
  "paths": {
      "@components/*": ["components/*"],
      "@lib/*": ["lib/*"]
    }
}
// This should work ✅
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
     //...
    "baseUrl": ".",
    "paths": {
      "@components/*": ["components/*"],
      "@lib/*": ["lib/*"]
    }
  },
  "include": ["next-env.d.ts", "twin.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"],
}

答案 2 :(得分:5)

我不知道为什么现在这个我正在努力的第11次(但没有前10次),但是df$col1 <- factor(df$col1) levels(df$col1) <- repl df$col1 <- as.character(df$col1) # optional, if you want character and not factor df # col1 # 1 blue # 2 blue # 3 blue # 4 blue # 5 blue # 6 yellow # 7 yellow # 8 yellow # 9 red # 10 red # 11 red # 12 red # 13 red 似乎是秘密的酱汁,而且文档中的例子显然是指向一个特定的文件(并省略了文件扩展名)。

/*

答案 3 :(得分:3)

pkestikar 说,tsconfig-paths-webpack-plugin 可以帮助解决这个问题。使用 yarn add --dev tsconfig-paths-webpack-plugin 将其保存在 devDependencies 上,在 next.config.js

上添加以下配置
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')

module.exports = {
  resolve: {
    plugins: [new TsconfigPathsPlugin({ configFile: "./tsconfig.json" })]
  }
}

我的路径开始使用它。这是我的tsconfig.json

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

这里是一个组件的导入。

import { Button } from '@/components/Button/Button'

它也适用于 import { Button } from 'components/Button/Button'

答案 4 :(得分:3)

开箱即用,它不适用于 tsc 或 ts-node。 但是对于一些包(tsc-alias 和 module-alias),它可以工作。 不需要 babel 或 webpack 设置。

library(lubridate)
library(tidyverse)

dummy <- data.frame(dumcol =seq.Date(as.Date('2020-01-01'),as.Date('2020-12-31'),by='week'))

dummy %>%
mutate(week=week(dumcol),months=month(dumcol,label=T)) %>% 
select(week,months)-> dummy

cov %>%
select(year_week) %>%
separate(year_week,c('year','week')) %>% 
mutate(week=as.numeric(week)) %>% 
left_join(dummy,by='week') %>% 
mutate(new_col=paste0(year,'-',months))

与 TSC 合作

添加 tsc-alias (https://www.npmjs.com/package/tsc-alias) 作为开发依赖

// tsconfig.json

{
  "compilerOptions": {
    ...
    "baseUrl": "./src",
    "paths": {
      "@common/*": ["common/*"],
      "@services/*": ["services/*"],
    },
    ...
  },
}

并将其添加到您的构建命令中

yarn add --dev tsc-alias

使用 TS-NODE

添加模块别名https://www.npmjs.com/package/module-alias)依赖

"build": "tsc && tsc-alias",

创建一个引用所有别名的文件

yarn add module-alias

并将其作为第一次导入导入到您的入口脚本中

// src/paths.ts

import 'module-alias/register';
import { addAliases } from 'module-alias';

addAliases({
  '@common': `${__dirname}/common`,
  '@services': `${__dirname}/services`,
});

答案 5 :(得分:1)

如果您将 Webpackts-loader 一起使用,但在尝试上述所有答案后仍然无法正常工作,您可能需要在 Webpack 配置的解析部分使用插件文件 - tsconfig-paths-webpack-plugin;因此它遵循您在编译时放入 tsconfig.json 文件的路径。

来源 - https://github.com/TypeStrong/ts-loader#baseurl--paths-module-resolution

答案 6 :(得分:0)

这可能对某人有所帮助-如果您使用tsc或工具将TS代码编译到单独的文件夹(例如disttsconfig-paths注册不会 解决问题。我有这样的tsconfig.json:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "lib": ["dom", "esnext"],
        "baseUrl": ".",
        "jsx": "react",
        "removeComments": true,
        "sourceMap": true,
        "outDir": "dist"
        "rootDir": ".",
        "paths": {
            "shared/*": ["./shared/*"],
        }
    },
    "include": ["./client/**/*", "./server/**/*"]
}

您会看到,诸如shared/someFolder/someScript之类的路径将正确解析到我项目中的shared文件夹,这比许多相对的../../../../路径而言是一种负载清理程序。

但是,这引发了我错误:

➜  game git:(game-dev) ✗ node --inspect -r tsconfig-paths/register dist/server/runProd.js
Debugger listening on ws://127.0.0.1:9229/f69956aa-d8d6-4f39-8be1-9c3e8383d4be
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
internal/modules/cjs/loader.js:584
    throw err;
    ^

Error: Cannot find module 'shared/types/UserTypes'

我做了一些挖掘,发现tsconfig-paths生成的tryPaths数组具有相对于project / cwd base的绝对URL,而不是build dist文件夹。

inspect screengrab

回想起来,这似乎很明显。使用该库似乎没有一种明显的方法来解决这个问题,因此我通过将tsconfig.json复制到dist文件夹中并运行node -r tsconfig-paths/register main.js来解决了这个问题。

答案 7 :(得分:0)

即使设置了基本URL,也请检查其是否在默认值“ ./”上 然后应将其更改为“ src”,只有这种方式对我有用。

答案 8 :(得分:-1)

我不得不使用 babel 来编译代码

npm i -D @babel/cli @babel/core @babel/node @babel/preset-env @babel/preset-typescript babel-plugin-module-resolver

然后在构建命令上

"build": "babel src --extensions \".js,.ts\" --out-dir dist --copy-files --no-copy-ignored"

还有 babel.config.js

module.exports = {
presets: [
    [
        '@babel/preset-env',
        {
            targets: {
                node: 'current'
            }
        }
    ],
    '@babel/preset-typescript'
],
plugins: [
    ['module-resolver', {
        alias: {
            '@config': './src/config',
            '@modules': './src/modules',
            '@shared': './src/shared'
        }
    }]
],
ignore: [
    '**/*.spec.ts'
]

}

相关问题