使用TypeScript模块系统获取普通JavaScript文件
我正在使用Visual Studio使用TypeScript创建一个ASP.NET Core 2.2 web应用程序,我已经从我在网上找到的npm包中包括了使用TypeScript模块系统获取普通JavaScript文件,javascript,asp.net,typescript,requirejs,bundling-and-minification,Javascript,Asp.net,Typescript,Requirejs,Bundling And Minification,我正在使用Visual Studio使用TypeScript创建一个ASP.NET Core 2.2 web应用程序,我已经从我在网上找到的npm包中包括了two.js库以及two.d.js(TypeScript声明文件) 问题是,我不明白如何让模块工作(也许它与two.js无关,但通常在模块中使用普通JavaScript) two.js文件使用JSDoc,但据我所知,没有任何导出 因此,我的项目包含以下文件(,和): 开始时,site.js文件正在导入two.js和something.ts:
two.js
库以及two.d.js
(TypeScript声明文件)
问题是,我不明白如何让模块工作(也许它与two.js
无关,但通常在模块中使用普通JavaScript)
two.js
文件使用JSDoc,但据我所知,没有任何导出
因此,我的项目包含以下文件(,和):
开始时,site.js
文件正在导入two.js
和something.ts
:
// this uses the 'two.d.js' file and I get intellisense
import { Two } from "./two";
// this is some .ts file
import { Something } from "./something";
// create the Two.js instance
let placeholder = document.getElementById('placeholder');
// this line is what I want to get running
let twojs = new Two({ width: 1900, height: 885 }).appendTo(placeholder);
但是,当编译site.ts
时,我尝试的任何模块选项都会在浏览器中失败:
导出而失败
未在编译的站点的第一行中定义。js
文件:
Object.defineProperty(exports, "__esModule", { value: true });
/something
和/two
的“404未找到”而失败。
TypeScript编译器不会将.js
扩展名附加到本机浏览器import
语句,因此无法加载这些文件。但是,如果在TypeScript中添加扩展名,则会出现编译错误Two
不是构造函数”异常。
代码被编译成这样,我可以看到所有.js
文件都正确加载,但是我想问题是two.js
不会以本机方式导出任何内容:
define(["require", "exports", "./something", "./two"], function (require, exports, something, two_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
let placeholder = document.getElementById('placeholder');
// Two is not a constructor
let twojs = new two_1.Two({ width: 1900, height: 885 }).appendTo(placeholder);
});
理想情况下,我希望每页都有一个捆绑的.js文件,以减少模块加载器服务器的往返,但我愿意接受其他选项。two.js没有导出任何内容,而是将
two
作为全局变量公开,因此two.d.ts
在对模块进行类型注释时是错误的(事实上,two.js
不符合“模块”的条件)。您需要先更正它
two.d.ts
中用declare
关键字替换所有顶级export
关键字。这将告诉tstwo.js
不是一个模块,而是公开一些全局变量site.ts
现在可以直接引用Two
全局变量,不再需要import
。作为一种良好的做法,建议在此文件顶部放置一个三斜杠指令以显示依赖关系。捆绑时,这也会将Two.js
的内容放在site.js
之前d(见下一步)
define(["require", "exports", "./something", "./two"], function (require, exports, something, two_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
let placeholder = document.getElementById('placeholder');
// Two is not a constructor
let twojs = new two_1.Two({ width: 1900, height: 885 }).appendTo(placeholder);
});
/// <reference path="./two.js" />
let twojs = new Two({ width: 1900, height: 885 }).appendTo(placeholder);
{
"include": [...],
"compilerOptions": {
"module": "amd",
"outFile": "bundle.js",
"allowJs": true // to include `two.js` into the bundle
}
}
<script data-main="scripts/bundle" src="scripts/require.js"></script>