【问题标题】:Typescript require not working [duplicate]打字稿不需要工作[重复]
【发布时间】:2017-02-23 23:28:58
【问题描述】:

我有 3 个打字稿文件:main.ts、print.ts、log.ts

我安装了节点模块并使用 typescript 编译器 - tsc main.ts - 来编译 .ts 文件。 之后,我尝试使用npm start 运行 index.html,但是 console.log 说 require 没有定义。我还缺少什么吗?我使用 Visual Studio 代码编辑器。

INDEX.HTML

<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<title>this is the title</title>

<style type="text/css">

</style>

</head>

<body>

<div id="wrapper">
</div>

<script type='text/javascript' src='main.js'></script>

</body>

</html>

MAIN.TS

import log = require('./log')
import print = require('./print')
log.logMessage();
print.printMessage();

PRINT.TS

export function printMessage() {
   console.log('print');
}

LOG.TS

export function logMessage() {
   console.log('log');
}

Console.log 应该说 'log' 和 'print',但它没有。

【问题讨论】:

  • 导出函数时可以直接调用。试试你的 main.ts: log();和打印();
  • 我认为您想要const log = require('./log');import log from './log';。如果这不是在某处引发错误,我会感到惊讶。
  • 是的,在你的打字稿中: import { logMessage} from "./log";不需要
  • 必须有人定义浏览器中的“要求”是什么。并且没有必要为此目的捆绑您的应用程序。你可以使用 systemjs (david-barreto.com/how-to-use-typescript-with-systemjs) 或者如果你想让你的生活更轻松一些 - 基于 systemjs 的 jspm (jspm.io)。

标签: javascript typescript


【解决方案1】:

您的代码很好。您问题的重要部分是

但是 console.log 说 require 没有定义

require用于node的模块系统,称为CommonJS。浏览器默认不理解这个系统。您必须使用捆绑器,例如 webpackfuse-box

TypeScript 无法真正捆绑您的应用程序:-/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-01
    • 2022-11-09
    • 2020-07-07
    • 2013-08-11
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 2020-11-08
    相关资源
    最近更新 更多