javascript - 在 Angular 6 组件中使用外部 js 文件

标签 javascript angular import angular6

我正在尝试在我的 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 文件中:

  1. import * as mymodule '../../testfile.js'
  2. "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/

相关文章:

python - 如何重新加载在另一个文件中导入的Python模块?

Javascript 检测到零个 anchor

javascript - 将 PHP 数组传递给 HTML 页面。

javascript - ProtoBuf.js 如何在编码对象时过滤额外字段

index.html 文件中的 Angular 环境变量

Angular:在子路由上设置特定的路由链接处于事件状态

javascript - 从包含瑞典字符的模型字符串设置 javascript 变量

javascript - Angular 2 中的 Trevor JS 爵士

python - 如何导入同级以便 python 可以运行文件和下游脚本?

python 队列与队列?