javascript - 在 Angular 6 组件中使用外部 js 文件
问题描述
我正在尝试在我的 Angular 6 应用程序中使用 js 文件。我遵循的步骤如下:
1. 创建testfile.js
文件:
var testa = function () { function testMethod() { console.log('hello'); } } var testmodule = new testa(); module.exports = testmodule;
2. 在angular.cli.json
。出于测试目的, tesfile.js 位于与以下位置相同的位置angular.cli.json
:
"scripts": [ "testfile.js" ],
3. 在 typings.d.ts 文件中,声明它:
declare var testmodule: any;
4.在ts文件中,尝试将其用作:
public ngOnInit() { testmodule.testMethod() }
但是当使用角度组件时,控制台中的警告是:
Uncaught ReferenceError: testmodule is not defined
我尝试了另一种选择,例如将 .ts 文件中的 js 文件导入为:
import * as mymodule '../../testfile.js'
"allowJs": true
但这也不能识别 testmodule 或 testfile。
我在这里做错了什么?
解决方案
我做了一个演示:https ://codesandbox.io/s/4jw6rk1j1x ,像这样:
testfile.js
function testa() {}
testa.prototype.testMethod = function testMethod() {
console.log("hello");
};
var testmodule = new testa();
export { testmodule };
而在main.ts
import { enableProdMode } from "@angular/core";
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";
import { AppModule } from "./app/app.module";
import { environment } from "./environments/environment";
import { testmodule } from "./testfile";
testmodule.testMethod();
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic()
.bootstrapModule(AppModule)
.catch(err => console.log(err));
您可以在控制台选项卡上看到“你好”文本
请注意,我在testfile.js
推荐阅读
- cassandra - 无法使用 java datastax 驱动程序进行更新插入
- javascript - 在反应中处理用户输入。如何将 [e.target.name] 连接到另一个字符串
- autohotkey - 如何将名称转换为自定义电子邮件地址?(即First.Last,F.Last@xxx...)
- c# - 在查看 ASP.NET MVC 中调用存储过程
- php - php下拉框变量中的空格
- vb.net - VS2017 误导性错误线路识别
- amazon-dynamodb - 映射地图时出现 DynamoDBMappingException
属性 - swift - 如何使用 Swift 中的 nextDate 函数获取给定日期的下个月日期?
- content-security-policy - 将 Content-Security-Policy 与 modernizr 一起使用的当前最佳实践是什么?
- javascript - 悬停没有颜色