javascript - Typescript 2 — 使用 ES6 导入和要求?

标签 javascript angular typescript module webpack

我在使用 ES6 模块的 Angular2 应用程序中导出了一个 class:

//File = init.todos.ts

export class Init {
   load() {
      ...
    }
}

我正在通过以下方式从另一个组件导入此类:

//File = todo.service.ts

import { Init } from './init.todos'

它按预期工作。

但是,如果我将加载机制更改为 commonjs :

//File = init.todos.ts
export class Init {
    load() {
       ...
    }
}
 module.exports.Init = Init;

要求它:

//File = todo.service.ts
var  Init = require("./init.todos");

——我得到了这些错误:

...myApp/src/app/todo.service.ts (4,13): Cannot find name 'require'.) ...myApp/src/app/todo.service.ts (12,14): Property 'load' does not exist on type 'TodoService'.)

enter image description here

问题:

如何使用 require 加载 commonjs 模块?

Tsconfig.json:

{
    "compileOnSave": false,
    "compilerOptions": {
        "outDir": "./dist/out-tsc",
        "baseUrl": "src",
        "module": "system",
        "sourceMap": true,
        "declaration": false,
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "target": "es5",
        "typeRoots": [
            "node_modules/@types"
        ],
        "lib": [
            "es2016",
            "dom"
        ]
    }
}

配置文件如下:

tslint.json

tsconfig.json

package.json

angular-cli.json

webpack.config.js

最佳答案

version 1.5 , Typescript采用了导入的ES6风格。

您可以“按原样”保留您的代码

//File = init.todos.ts

export class Init {
   load() {
      ...
    }
}

//File = todo.service.ts

import { Init } from './init.todos'

通过将 tsconfig.json 中的属性 module 移动到 commonjs,转译器将生成 commonjs 兼容的 javascript,这将使您受益,并为完整的 nodeJS 生态系统做出贡献。

"compileOptions": {
    ...
    "module": "commonjs"
    ...
}

如果您希望在 typescript 代码中导入现有的 NodeJS 模块,可能会发生一些事情

  • 模块附带嵌入式 Typescript 定义文件(“package.json”中有一个“typings”条目)。在这种情况下,使用 ES6 语法导入模块就可以了(import * as blah from 'blah')。 immutable.js就是这样一个库的一个很好的例子

  • 该模块不附带定义文件,但在 DefinitelyTyped 上提供了一个。 , 简单地

    • 运行 npm install @types/blah 获取项目中的定义
    • 并照常导入模块:import * as blah from 'blah'
  • 模块没有定义文件

    • 您可以制作一个,只需将其命名为 blah.d.ts 后将其添加到您的项目中即可。 DefinitelyTyped 有 a guide对此
    • 你可以决定不打字,只需使用 NodeJS require() const blah = require('blah')blah 的类型将是 any (这实际上意味着 blah 选择不输入)

(为了完整起见,我可以添加自 1.8 以来可用的 allowJS compiler option,但这本身就是一个完整的主题)

关于javascript - Typescript 2 — 使用 ES6 导入和要求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42814582/

相关文章:

javascript - 使用sessionStorage代替共享服务可以吗

java - 将 Java 对象传递给 Angular 以满足特定需求

javascript - Angular 2 ng-model-options ="{updateOn: ' 改变模糊'}”

typescript - 更新来自处理响应延迟和其他错误的 Web 服务的数据

javascript - 强制浏览器重新加载缓存而不使用服务器端代码

javascript - Framework7如何使消息自动向下滚动?

javascript - 我如何制作这样的菜单?

javascript - Ionic 4 上传截图到服务器

node.js - 在 typescript 中找不到 'autobind-decorator' 的声明文件

javascript - 如何判断一个字符串是否是一个数组?