在Angular组件中引用两个JavaScript文件的问题

问题描述 投票:1回答:1

我有两个类似下面的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喜欢有两个独立的JS文件。当我在一个纯HTML文件中执行此操作并包含这两个脚本时,这很好用。关于我的Angular组件我会错过什么来阻止我尝试做什么?

javascript angular
1个回答
0
投票

那是因为typescript正在编译所有关闭的匿名函数。所以你的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()

然后孩子将有权访问该功能。

© www.soinside.com 2019 - 2024. All rights reserved.