met*_*ker 9 javascript jquery angular-cli angular
我在AngularJS项目中使用基于jQuery的select2组件.我和这里的人有类似的问题:https://github.com/fronteed/icheck/issues/322,并使用那里的建议解决了它.准确地说,我TypeError: $(...).select2 is not a function在没有使用该建议时收到错误.
即我在Webpack的配置中添加了下一行@angular/cli/models/webpack-configs/common.js.
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]
Run Code Online (Sandbox Code Playgroud)
它是在angular/cli中启用jQuery的最佳方法吗?
我不认为在https://github.com/angular/angular-cli/wiki/stories-global-lib中做同样的事情是正确的,因为
a)webpack捆绑jQuery而无需在脚本中指定它
b)TypeError: $(...).select2 is not a function当你按照故事中所描述的那样包含它时,它仍会抛出错误.
Hir*_*ekh 26
我在我的项目中使用jQuery如下.
安装jQuery
npm install --save jquery
Run Code Online (Sandbox Code Playgroud)安装jQuery类型定义以进行类型检查.
npm install --save-dev @types/jquery
Run Code Online (Sandbox Code Playgroud)在angular-cli.json文件中的"scripts"数组中添加jquery文件的refenece.
"scripts": [
"../node_modules/jquery/dist/jquery.min.js"
]
Run Code Online (Sandbox Code Playgroud)在要使用的任何组件中导入jquery.
import * as jQuery from 'jquery';
Run Code Online (Sandbox Code Playgroud)而已.同样的方法也可以用到其他库一样moment.js,d3.js等等.
我能够通过公开 Webpack 来实现我所需要的。使用ng eject命令。
首先,使用安装 jQuery npm install -S jquery(我也安装了npm install -S select2,因为我也需要它)。
然后,确保您备份了 package.json 文件,因为在ng ejectAngular CLI 期间会尝试将其 Webpack 依赖项添加到 package.json 中。
ng eject完成工作后,webpack.config.js我在里面添加了
// ... Inside require/imports part
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
// ... Inside `plugins` section of Webpack configuration
new ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
Run Code Online (Sandbox Code Playgroud)
现在 select2$(...).select2正确地将函数添加到全局 jQuery 对象!
要在 .ts 文件中将 jQuery 与 select2 结合使用,您可以在该文件的开头添加下一行:
import "select2";
import "jquery";
declare var $: any;
// Somewhere deep within component
// ...
$(this.input.nativeElement)
.select2(config)
.on("change select2:select select2:unselect", (e: any) => this.onSelect2ElementChange(e));
// ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17298 次 |
| 最近记录: |