我正在尝试在我的 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() }
但是当使用 Angular 组件时,控制台中的警告是:
Uncaught ReferenceError: testmodule is not defined
我尝试了另一种选择,比如将 js 文件导入 .ts 文件中:
import * as mymodule '../../testfile.js'
"allowJs": true
但这也没有识别测试模块或测试文件。
我在这里做错了什么?
最佳答案
我做了一个演示: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
关于javascript - 在 Angular 6 组件中使用外部 js 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52776717/