导入jQuery插件' jquery.shorten'在TypeScript / Angular 4中

时间:2017-08-22 07:22:13

标签: jquery angular typescript

我想使用jquery.shorten在Ionic项目中使用名为npm的jQuery插件。

installig的命令是npm install jquery.shorten --save

我已成功包含jQuery,我可以在我的项目中使用它。但无法使用jquery.shorten

以下是我用来包含jQueryjquery.shorten的代码。它位于角项目的app.module.ts -

import * as $ from 'jquery';
import 'jquery.shorten';

我在控制台中看到的错误是 -

  

未捕捉错误:找不到模块" jquery.shorten"

我也试过以下。这次所有控制台错误消失了。但我无法找到使用它的方法。

import * as shortMe from 'jquery.shorten';

它应该用作$(".dynamic-multiple-elements").shorten()

我已经跟踪了很少instructions来包含它。但似乎没有任何效果。 我可以在jquery.shorten中看到包含所需js文件的文件夹node_modules

我无法使用this solution,因为我的元素是动态的,而且很多。

2 个答案:

答案 0 :(得分:0)

您可以在Angular中看到here如何使用JQuery和其他第三方全局变量。

如果没有InjectionToken的简单方法,您可以这样做:

npm install jquery --save.

npm install jquery.shorten --save.

在angular-cli.json

中添加两个脚本引用
...
"scripts": [
   "../node_modules/jquery/dist/jquery.min.js",
   "../node_modules/jquery.shorten/src/jquery.shorten.min.js"
],
...

如果你不使用angular-cli将脚本放在webpack中。

在任何组件中使用:

declare let $ : any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

   ngOnInit(): void {
      console.log($);
      $('#text').shorten();    
   }
}

要测试的组件html

<p id="text">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p>

答案 1 :(得分:0)

好的,这是我已经实现的(using this),它完美地运作。

<强> 1。 app.module.ts - 这样我的导入就可以在所有组件中使用。

import 'jquery';
import 'jquery.shorten/src/jquery.shorten';

2. 我将以下代码添加到webpack.config.js -

plugins: [
   new webpack.ProvidePlugin({
       $: "jquery",
       jQuery: "jquery"
    })
]

3。declare let $: any;中声明变量declare let jQuery: any;home.ts,我想同时使用jQueryjquery.shorten

问题 - webpack.config.js文件夹下有node-modules个文件。在转移代码或重新安装npm期间,它很有可能被替换。

期望 - 即使项目文件已转移,更改仍应保留。

如果有可能,我希望解决方案类似于this solution