首页 > 解决方案 > 在 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 文件导入为:

  1. import * as mymodule '../../testfile.js'
  2. "allowJs": true 但这也不能识别 testmodule 或 testfile。

我在这里做错了什么?

标签: javascriptangularimportangular6

解决方案


我做了一个演示: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


推荐阅读