在浏览器中使用的翻译打字稿 [英] Transpile typescript for use in browser
问题描述
我正在尝试用Typescript编写前端代码,并希望导出该代码,以便我的浏览器可以加载
< script src = ...>< / script>
。
I am trying to write my frontend code in Typescript and want to export the code, that my browser can load in
<script src="..."></script>
.
我是通过browserify和tsify实现的。我的麻烦是无法在全局名称空间中访问我的代码。当然,在< script>
标记中加载脚本将执行该脚本,但是如果我希望像在库中使用的函数库那样加载脚本,该怎么办< script>
s或类似的内容?
I did so by way of browserify and tsify. My trouble is that not on my code is accessible in the global namespace. Loading the script in a <script>
tag will execute it, sure, but what if I intend it to be loaded like a library of functions that can be used in inline <script>
s or similar?
更新
例如
index.ts
function foo(): void {
console.log("bar");
}
使用以下conf编译将生成以下javascript
Compiling with the following conf produces the following javascript
tsconfig.json
{
"compilerOptions": {
"module": "UMD",
"target": "es5",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true
}
}
index.js
function foo() {
console.log("bar");
}
这很好。但是,如果index.js导入了某些内容,例如我的通知
函数,然后我得到这个
This is fine. However, if index.js imports something, e.g. my notification
function, then I get this
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(["require", "exports", "./notifications"], factory);
}
})(function (require, exports) {
"use strict";
var notifications_1 = require("./notifications");
notifications_1.notification("blerp");
function foo() {
console.log("bar");
}
});
现在 foo
被包装在某个范围内,并且在我将其加载到我的网站时不可用:< script src = require.js data-main = index>< / script>
Now foo
is wrapped in some scope, and is not available when I load it on my website: <script src="require.js" data-main="index"></script>
foo is undefined
推荐答案
在模块加载作为浏览器的本机JavaScript功能登陆浏览器之前,您可以使用RequireJS或SystemJS之类的库来加载模块。
Until module loading lands in browsers as a native JavaScript feature, you can use a library such as RequireJS or SystemJS to load modules.
使用RequireJS时,只需传递编译器选项:
When using RequireJS, you simply pass the compiler option:
-module UMD
然后将RequireJS指向您的主文件:
And then point RequireJS at your main file:
<script src="require.js" data-main="app"></script>
然后按需异步加载模块,生活就很好了。
Modules are then loaded asynchronously on demand and life is good.
这篇关于在浏览器中使用的翻译打字稿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!