[英]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.