[英]Using external js file in angular 6 component
我正在尝试将js文件用于我的angular 6应用程序。 我遵循的步骤如下:
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));
您可以在控制台选项卡上看到“hello”文本
请注意,我在testfile.js
做了一些更改
在angular-cli.json文件中提供对脚本的引用。
"scripts": [
"../path_of_script"
];
然后添加typings.d.ts
declare var testModule : any;
将其导入您想要使用它的位置
import * as myModule from 'testModule';
您可以在angular.json中导入外部JS
"scripts": [ "node_modules/jquery/dist/jquery.min.js", "node_modules/popper.js/dist/umd/popper.min.js", "node_modules/bootstrap/dist/js/bootstrap.min.js", "import "../../../assets/js/counter" ]
如果要为特定的html组件导入JS文件,则可以在yourComponent.ts中 导入 js文件
就像:
import { Component, OnInit } from '@angular/core';
import "../../../assets/js/counter";
你可以在这里看到我在特定的HTML页面中导入了counter.js .
在这一行中“ ../../../assets/js/counter ” 计数器是一个js文件名。 您无需在文件名后添加.js 。
请确保您仔细设置路径../../ ..
您可以将所有外部js文件存储在assets / js文件夹中。 然后,您可以在特定的component.ts中导入特定的js文件。
这对我来说非常适合6角。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.