jQuery没有在bootstrap-sass中定义

我使用angular-cli引导了Angular 2应用程序。 一切都很简单,直到我决定使用bootstrap模态。 我只是复制了我们的另一个不使用angular-cli的项目中打开模式的代码。 我在angular-cli.json文件中将jquery和bootstrap依赖项添加到了脚本中。 jQuery在项目中被识别,但是当我尝试运行this.$modalEl.modal(options)在angular度组件中我得到一个错误, jQuery is not defined

其实jQuery是导入到项目,但作为一个全球$ 。 我已经做了一些挖掘,显然引导期望jQuery作为一个“jQuery”variables传递给它。 它不给大鼠的屁股关于$

我可以将jQuery作为webpack.config.js文件中的一个variables来webpack.config.js就像我们在其他项目中webpack.config.js那样:(为简洁起见,省略了许多代码)

 var jQueryPlugin = { $: 'jquery', jquery: 'jquery', jQuery: 'jquery' } exports.root = root; exports.plugins = { globalLibProvider: new webpack.ProvidePlugin(webpackMerge(jQueryPlugin, { svg4everybody: 'svg4everybody/dist/svg4everybody.js' })) } 

但是angular-cli dev团队决定不让其他开发者干涉webpackconfiguration文件。 多谢你们! 非常想你。

我试过直接导入jQuery到Angular组件和一些其他的东西在这里提到https://github.com/angular/angular-cli/issues/3202 (添加导入到vendor.ts文件,然后添加vendor.ts脚本数组在angular-cli.json),但没有任何工作。

说实话,我很生气,这样一个微不足道的问题,如添加jquery依赖关系,在angular度cli bootstrap使用是这样一个雷区。

你有没有处理类似的问题?

步骤1

 npm install jssha --save [using jssha for this demo] It it is your own custom file place it in the scripts array of angular-cli.json skip this step 1 

第二步

 Add the jssha scripts file in .angular-cli.json file "scripts": [ "../node_modules/jssha/src/sha.js" ] Step three Adding a var in component to be used as a global variable //using external js modules in Angular Component declare var jsSHA: any; // place this above the component decorator shaObj:any; hash:string; this.shaObj = new jsSHA("SHA-512", "TEXT"); this.shaObj.update("This is a Test"); this.hash = this.shaObj.getHash("HEX") 

看看@这个链接 。 它有一个工作的例子和types与没有它类似的问题。 我在这个项目中使用了引导和jquery的Angular,你也可以检查回购。

你的情况你需要添加jQuery文件

像这样在你的angular-cli.json中

  "styles": [ "../node_modules/bootstrap-v4-dev/dist/css/bootstrap.min.css", "styles.css" ], "scripts": [ "../node_modules/jquery/dist/jquery.js", "../node_modules/tether/dist/js/tether.min.js", "../node_modules/bootstrap-v4-dev/dist/js/bootstrap.min.js" 

然后在组件中声明。 declare var $: any;

这应该工作。

UPDATE

我继续使用我刚才提到的步骤,使用Angular中的jquery创build一个引导模式。

它的工作原理检查这个页面链接 – LINK 。

如果你想检查相同的LINK链接的源代码。

我发布的答案来自这个链接,这是我在Angular LINK上的页面

我没有特别使用Angular 2的Bootstrap,但是我已经使用了Angular 1,情况也是一样的,Bootstrap的常规版本是为了使用jQuery而devise的,而不是用Angular构build的。 您当然可以安装jQuery,但是在Angular的上下文中,Javascript可能无法正常工作。

最简单的解决scheme是使用Angular构build的版本,我认为ng-bootstrap是其中最为突出的一个。 我自己并没有使用它,但我已经使用Angular 1的angular-ui-bootstrap,这似乎是同一个项目的Angular 2对应的。

或者,你可以自己把它包装在一个指令中 ,但是如果你能得到ng-bootstrap来做你想做的事情 ,我会避免这样做,因为这样做会更有效。

您可以使用命令ng eject让Angular CLI生成webpack.config文件。

然后像以前一样将jQuery作为一个variables公开。