我使用的是角12,我想在我的ts组件中使用自定义的JavaScript文件。为了实现这一目的,我理解我需要将custom.js文件添加到angular.json中的“脚本”部分,并在我的ts组件中声明如下:
我的custom.js文件
function test() {
alert("Hello!");
}在app.component.ts中
import { Component, OnInit } from "@angular/core";
import { Subject, Observable } from "rxjs";
declare function test(): void;
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"],
})
export class AppComponent implements OnInit {
....
...
test();在angular.json文件中,我向custom.js添加了路径
.....
"scripts": [
"src/assets/js/custom.js"]
.....这很好,当de app被服务时,警报信息被正确地显示出来。
假设现在我想在我的custom.js文件中使用Javascript库,例如"sharp":
import {sharp} from "sharp";
function test() {
alert("Hello!");
const image = sharp("file.jpg");
}现在,当我通过"ng s“提供应用程序时,我可以在浏览器的控制台中看到以下错误:
Cannot use import statement outside a module当然,这指向我的custom.js文件的“从”sharp“行导入{sharp}”。
我一直试图:
problem.
我的问题是:
在我的角度项目中,我应该在哪里以及如何声明为了让我的custom.js工作而需要/使用sharp库?
谢谢
发布于 2022-02-14 09:58:45
要将另一个js文件导入另一个js,sharp.js应该导出函数sharp()和test.js应该import { sharp } from './main.js';。然后测试可以使用sharp(),而您的Angulr项目只使用声明的函数test()。https://www.tutorialrepublic.com/faq/how-to-include-a-javascript-file-in-another-javascript-file.php
发布于 2022-02-14 09:59:56
首先,导出函数test.
export function test() {
alert('custom js');
}将其导入您的app.component中。
import {Component} from '@angular/core';
import * as yourlib from 'src/custom.js';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(){
yourlib.test();
}
}https://stackoverflow.com/questions/71109812
复制相似问题