[英]Problem referencing two JavaScript files within Angular component
我有两个如下的Javascript文件,一个父级定义一个方法,一个子级从父级调用该方法:
parent.js
function HelloWorld() {
alert('HelloWorld');
}
child.js
HelloWorld();
在我的Angular组件中,我像这样引用脚本:
import { Component } from '@angular/core';
import 'src/app/parent.js';
import 'src/app/child.js';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'my-dream-app';
}
运行该应用程序时,在控制台中收到一条错误消息,指出:
未捕获的ReferenceError:未定义HelloWorld
如果我从Parent.js内调用HelloWorld(),它将运行良好; 但似乎Angular likes没有两个单独的JS文件。 当我只在一个纯HTML文件中执行此操作,并在其中包含两个脚本时,就可以正常工作。 我的Angular组件缺少什么来阻止我尝试做的事情?
那是因为打字稿正在将所有内容编译为封闭的匿名函数。 因此,您的parent.js
将被编译为
(function(module, exports) {
function helloWorld () {
console.log('hello')
}
/***/ }),
而且您无法访问该范围。
但是,如果您执行export function helloWorld() {...}
,然后将其导入到child.js
例如:
child.js
import {helloWorld} from '../path/to/child.js'
helloWorld()
要么
import * as parent from './parent.js';
parent.helloWorld()
那么孩子将可以使用该功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.