简体   繁体   English

如何在Angular 4组件中添加Javascript库?

[英]How to add a Javascript library to Angular 4 component?

I am trying to figure out how to import JavaScript files ONLY to a specific component. 我试图弄清楚如何将JavaScript文件导入到特定组件。

I put the following code directly into my component: 我将以下代码直接放入组件中:

import "../../vendor/datatables/js/jquery.dataTables.min.js";
import "../../vendor/datatables-plugins/dataTables.bootstrap.min.js";
import "../../vendor/datatables-responsive/dataTables.responsive.js";

But it fires an error saying: 但这会引发一个错误:

Module not found: Error: Can't resolve 'jquery' in... 找不到模块:错误:在...中无法解析“ jquery”

Which makes me suspect that the files that depend on jQuery cannot find the jQuery library in this scope. 这使我怀疑依赖jQuery的文件在此范围内找不到jQuery库。

jQuery itself is put in the angular-cli.json file: jQuery本身放在angular-cli.json文件中:

"scripts": [
    "./vendor/jquery/jquery.min.js"
],

An alternative is to put all of those 3 external JS files into the angular-cli.json file as well, and it will work, showing the expected result from the user perspective. 一种替代方法是也将所有这三个外部JS文件都放入angular-cli.json文件中,并且它将起作用,从用户角度显示预期的结果。

But I would like to figure out how to avoid setting the JS globally for those that are used only in a few specific components. 但是我想弄清楚如何避免为仅在少数特定组件中使用的那些设置全局设置JS。

Thanks, please advise. 谢谢,请指教。

For example, to import jQuery to your component, you should write: 例如,要将jQuery导入您的组件,应编写:

import * as $ from 'jquery';

Which means "Import all and use as "$" from "jQuery"" . 意思是“全部导入并从“ jQuery”中用作“ $””

If you downloaded the library by yourself, without npm install , you can try the following (but I'm not sure that it will work): 如果您是在没有npm install情况下npm install下载该库,则可以尝试以下操作(但是我不确定它是否可以运行):

import * as $ from 'path/to/jquery';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM