【发布时间】:2017-08-06 11:26:16
【问题描述】:
我在使用 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): 找不到名称 'require'。) ...myApp/src/app/todo.service.ts (12,14): 类型“TodoService”上不存在属性“load”。)
问题:
如何使用 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"
]
}
}
这里是配置文件:
【问题讨论】:
-
发生这种情况是因为您拥有
"module": "system"。 SystemJS 中没有 require 函数。 -
在 tsconfig 中,将 "module" 更改为 "commonjs" 并保留 ES6 语法,例如`从'./init.todos'导入{初始化}。
-
@BrunoGrieder 哦,所以导入的模块会有
module.exports,但我仍然应该通过 es6 语法导入它? -
是的。 Typescript 不久前采用了 ES6 样式导入(1.5 或 1.7)。如果您使用
const x = require('blah'),您将使用 NodeJS/CommonJS 要求并且“丢失”类型,因为x将被映射到任何类型。这对于导入未键入的 JS 库可能很有用
标签: javascript angular typescript module webpack