我使用 angular-cli 引导了 Angular 2 应用程序。在我决定使用 bootstrap modal 之前,一切都很简单。我只是从我们不使用 angular-cli 的其他项目中复制了用于打开模式的代码。我在 angular-cli.json 文件中的脚本中添加了 jquery 和 bootstrap 依赖项。 jQuery 在项目中被识别,但是当我尝试在 Angular 组件内运行 this.$modalEl.modal(options)
时,我得到一个错误,提示 jQuery is not defined
。
实际上 jQuery 是作为全局 $
导入到项目中的。我做了一些挖掘,显然 bootstrap 希望 jQuery 作为“jQuery”变量传递给它。它不会给老鼠屁股 $
。
我可以将 jQuery
公开为 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
开发团队决定不让其他开发人员干预 webpack 配置文件。多谢你们!很为你着想。
我已经尝试将 jQuery 直接导入 Angular 组件以及此处提到的许多其他内容 https://github.com/angular/angular-cli/issues/3202 (将导入添加到 vendor.ts 文件,然后将 vendor.ts 添加到 angular-cli.json 中的脚本数组)但没有任何效果。
老实说,在angular-cli 中添加jquery
依赖与bootstrap
一起使用这种微不足道的问题让我很生气,这是一个雷区。
你处理过类似的问题吗?
最佳答案
第一步
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")
看看@这个link .它有一个工作示例和一个关于打字和不打字的问题。我在那个项目中使用了 bootstrap 和 jquery 以及 Angular,你也可以检查 repo。
在您的情况下,您需要添加 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;
这应该有效。
更新
我继续使用我提到的步骤在 Angular 中使用 jquery 创建 Bootstrap 模式。
有效 检查此 gh 页面链接 - LINK .
如果你想检查源代码同样检查LINK .
我发布的答案来自此链接 这是我在 Angular 上的页面 LINK
关于jQuery 未在 bootstrap-sass 中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45339209/