ES2015模块“此语法需要导入的帮助器,但找不到模块'tslib'”

时间:2018-10-14 10:42:06

标签: typescript

我有一个演示项目,我要在启用ES2015模块并将tslib用于外部TS帮助器的情况下编译为ES5:

package.json

{
  "name": "foo",
  "scripts": {
    "build": "tsc"
  },
  "dependencies": {
    "tslib": "^1.9.3"
  },
  "devDependencies": {
    "typescript": "^3.1.3"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "es2015",
    "outDir": "./lib",
    "rootDir": "./src",
    "importHelpers": true,
    "strict": true,
    "experimentalDecorators": true
  }
}

src / index.ts

function a(target: any) {
    return target;
}

@a
export class Foo {}

这会导致错误:

  

src / index.ts:5:1-错误TS2354:此语法需要导入的帮助程序,但找不到模块'tslib'。

lib/index.js正确编译时:

import * as tslib_1 from "tslib";
function a(target) {
    return target;
}
var Foo = /** @class */ (function () {
    function Foo() {
    }
    Foo = tslib_1.__decorate([
        a
    ], Foo);
    return Foo;
}());
export { Foo };

该问题如何解决?

12 个答案:

答案 0 :(得分:13)

Noob错误(我刚刚犯了)。试试:

npm add tslib

npm i

我个人在星期五退出之前做了一个git clean -fxd,但没有npm i,因此所有npm软件包都丢失了。 h!

答案 1 :(得分:10)

仅将tslib更新到最新版本,并且问题已修复。我已经安装了1.9.3,并更新为1.10.0

答案 2 :(得分:4)

将以下几行添加到tsconfig.json

"compilerOptions": {
    //...rest parameters

    "baseUrl": "./",
    "paths": {
      "tslib" : ["path/to/node_modules/tslib/tslib.d.ts"]
    },

答案 3 :(得分:3)

我的问题是编辑器使用的 TypeScript 版本与项目不同。

要解决这个问题:

  1. 打开命令面板(Mac 上为 Cmd+Shift+P。焦点文件必须是 .ts 或 .tsx,否则不会显示更改版本的选项)
  2. 选择“TypeScript:选择 TypeScript 版本...”
  3. 它显示了 VSCode 的 TS 版本和 Workspace 的(项目)版本,选择那个

或者点击底部栏中的版本号,如果它显示在那里:

答案 4 :(得分:2)

我的错误似乎是零星的,但可能是由于编辑“ node_modules”文件夹中的文件引起的。

我删除了

  • “ node_modules”文件夹
  • “ package-lock.json”文件

Ran ...“ npm install”

它现在正在工作。

注意:在删除文件之前,我尝试运行“ npm install”,但这不能解决问题。

答案 5 :(得分:1)

更新package.json中tslib的依赖项和devDependencies

{
   dependencies:{
     "tslib": "1.10.0",
   },
   devDependencies:{
     "tslib": "1.10.0",
   }
}

答案 6 :(得分:1)

在我的情况下,错误Cannot find module 'tslib'是由我的Angular存储库中的特殊构建器@nrwl/node:build引起的(我将nrwl/nx monorepo模式与NodeJS服务器用作应用程序之一)。 / p>

在编译输出中未包含tslib。在"externalDependencies": "none"的生产构建配置中设置angular.json解决了该问题。值得关注的是@vincastl:https://github.com/nrwl/nx/issues/2625

将其张贴在这里,因为这是我发现的试图解决此问题的第一篇文章,也许我并不孤单。

答案 7 :(得分:1)

npm i -g tslib

这解决了我的问题。没有 -g 它对我不起作用。

答案 8 :(得分:0)

the reference所述,仅将"modules": "commonjs"的模块分辨率设置为Node模式,而将"modules": "es2015"的模块分辨率设置为经典模式:

  

有两种可能的模块解析策略:Node和Classic。您可以使用--moduleResolution标志来指定模块解析策略。如果未指定,则默认值为--module AMD | Classic。系统| ES2015或其他节点

由于经典模式不了解node_modules,因此编译器无法解析tslib模块。

moduleResolution应该为ES2015模块明确设置:

...
"module": "es2015",
"moduleResolution": "node",
...

答案 9 :(得分:0)

将此行添加到<PropertyGroup>内的.csproj文件中:

<TypeScriptCompileBlocked>True</TypeScriptCompileBlocked>

答案 10 :(得分:0)

在您的项目中,只需运行

npm i tslib 

它包含所有的打字稿助手功能

答案 11 :(得分:0)

npm 安装

如果您在第一次打开新项目或存储库时看到此错误,则您可能只是尚未安装应用所需的模块。

在应用程序的目录中,只需运行:

npm install

相关问题