Typescript找不到已使用SystemJS映射的模块

max*_*pre 8 typescript tsc tsconfig systemjs

Typescript在此导入中找不到该模块import ga from 'googleAnalytics';

SystemJS知道在哪里找到模块,因为它已被映射到前面,如下所示:

map: {
    '@angular': 'node_modules/@angular',
    'rxjs': 'node_modules/rxjs',
    'underscore': 'node_modules/underscore/underscore-min.js',
    'googleAnalytics': '//www.google-analytics.com/analytics.js'
},
Run Code Online (Sandbox Code Playgroud)

我怎样才能提供类似的映射tsc

这个问题似乎指向了一个很好的方向:如何在Angular 2中避免使用非常长的相对路径进口?

Typescript 2.0似乎支持paths配置tsconfig.json.有没有办法下载Typescript 2.0?我可以为path配置提供一个http url(//www.google-analytics.com/analytics.js),就像我在使用SystemJS一样吗?如果没有办法下载Typescript 2.0,我怎么能用当前版本实现我想要的?

编辑

我得到的具体错误是:"找不到模块'ga'".

这是我的tsconfig.json:

{
    "compilerOptions": {
        "rootDir": "./",
        "target": "es5",
        "module": "system",
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "noImplicitAny": true
    },
    "exclude": [
        "node_modules",
        "front-end/node_modules",
        "typings/main",
        "typings/main.d.ts"
    ]
}
Run Code Online (Sandbox Code Playgroud)

Sta*_*olc 0

我想你明白,在打字稿编译的情况下,转译器正在寻找明确的类型文件。他需要知道外部模块的类型定义。我的情况是你有活动的nodejs模块解析(你有)并且你使用非相对路径(你有)你必须添加到你的项目node_modules目录(也许你已经有一个)并向这个目录添加googleAnalytics.d.ts文件或者您可以创建node_modules/googleAnalytics目录,然后在其中添加index.d.ts。谷歌分析的定义类型可以从 DefintelyTyped存储库下载

有关模块解析的更多信息请参见此处

编辑:根据您的评论,也许您必须将模块导出添加到谷歌定义文件中

declare module 'googleAnalytics' {
    export = UniversalAnalytics;
}
Run Code Online (Sandbox Code Playgroud)

  • 在“node_modules”中手动创建文件夹是一种非常糟糕的做法。您应该很少(如果不是从不)修改此文件夹。Typescript 编译器还会查找[环境模块声明](https://www.typescriptlang.org/docs/handbook/modules.html#working-with-other-javascript-libraries),这是 @jasonszhao 提出的,但它似乎谷歌分析类型定义不导出任何内容。 (2认同)