无法在Angular 6.0的Typescript中加载JavaScript
我参考了许多关于堆栈溢出的文章,以调用Angular6的typescript中的JavaScript方法,但没有一篇有效,首先,我正在寻找一个简单的函数,其中包含一个警报,该警报将在JavaScript中执行,并从typescript中调用,要求提供工作方法和详细说明,说明如何为JavaScript文件创建d.ts文件,以及所有配置文件(如angular.json、tsconfig.json等)的详细更改,如果可能,请为Angular6发布一个工作和测试的示例,如果它是NPM软件包,如moment is you can NPM install,以及类似的参考无法在Angular 6.0的Typescript中加载JavaScript,javascript,typescript,angular6,Javascript,Typescript,Angular6,我参考了许多关于堆栈溢出的文章,以调用Angular6的typescript中的JavaScript方法,但没有一篇有效,首先,我正在寻找一个简单的函数,其中包含一个警报,该警报将在JavaScript中执行,并从typescript中调用,要求提供工作方法和详细说明,说明如何为JavaScript文件创建d.ts文件,以及所有配置文件(如angular.json、tsconfig.json等)的详细更改,如果可能,请为Angular6发布一个工作和测试的示例,如果它是NPM软件包,如momen
import * as moment from 'moment';
然后像其他物体一样使用它
moment('dateStringToParse');
如果您想添加非NPM JavaScript,请将文件放在资产文件夹中,并将其包含在“脚本”中:[]angular cli json文件的一部分。我认为有很多实用工具可以为Angular6创建脚手架项目模板。其中最好的一个是有角度的cli 还请确保您的计算机中安装了节点。节点安装后,使用“npm安装-g@angular/cli”。对于mac/linux,请在命令之前使用“sudo” 得到确认后,创建一个项目文件所在的目录,然后将“cd”放入该目录。键入“ng新”。加载所有依赖项以及“TypeScript”和“WebPack”的配置需要几分钟的时间。Angular cli将隐藏webpack文件的配置,但在构建项目时会使用此配置 最后使用“ng serve”查看angular是否正常运行 angular cli的优点是,在开发代码时,它强制实施了最佳实践。我在我的一个SharePoint项目中使用它来构建购物车,我非常喜欢它 您还可以单击以下链接查看官方文档:
快乐编码 转到angular.json或angular cli.json(对于angular 4项目),添加一个脚本标记来引用外部javascript文件,比如demo.js,如下所示
"scripts":[
"./assets/demo.js"
]
"allowJS":true
export class AppComponent{
calljsfunction(){
console.log("inside ts file method");
var p1 = new Gemoetry.point(1,0)
}
}
转到tsconfig.json并添加“allowJS”,如下所示
"scripts":[
"./assets/demo.js"
]
"allowJS":true
export class AppComponent{
calljsfunction(){
console.log("inside ts file method");
var p1 = new Gemoetry.point(1,0)
}
}
将外部js文件添加到assets文件夹中,我们称之为demo.js
在app文件夹下添加appcomponent.d.ts,用于外部js文件组件的类型声明
在appcomponent.html中创建一个按钮,点击ts方法并从javascript调用js方法
<div>
<button (click)="calljsfunction()"> call external JS file</button>
</div>
在app.component.d.ts中实现d.ts
declare module MGeometry{
export interface Point{
x:number;
y:number;
new (x:number,y:number):Point;
}
export interface Line{
point1:Point;
point2:Point;
new (p1:Point,p2:Point):Point;
}
export interface Main{
point: Point;
line : Line;
}
}
declare var Geometry:MGeometry.Main;
在demo.js中
line : (function(){
function line(p1,p2){
this.point1 = {x: p1.x, y: p1.y};
this.point2 = {x: p2.x, y: p2.y};
}
return line;
} ) (),
在类似的行中,在demo.js文件中实现point函数我已经知道如何创建Angular6项目Tanuj,请重新阅读问题声明我说使用angular cli json配置文件的脚本部分,我没有提到脚本标记。是的,在angular cli json本身中使用脚本部分不起作用。我正在尝试加载自己的javascript,而不是从节点模块加载