jQuery没有在bootstrap-sass中定义

jQuery的 Webpack

GO

2020-05-28

我使用angular-cli引导了Angular 2应用程序。直到我决定使用bootstrap modal之前,一切都是轻而易举的。我只是从其他不使用angular-cli的项目中复制了用于打开模态的代码。我在angular-cli.json文件中的脚本中添加了jquery和bootstrap依赖项。jQuery在项目中是公认的,但是当我尝试this.$modalEl.modal(options)在角度组件中运行时,出现错误jQuery is not defined

实际上jQuery是导入到项目中的,但是是全局的$我做了一些挖掘,显然引导程序希望将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中的scripts数组),但没有任何效果。

老实说,我很生气,像在angular-cli中jquery使用依赖项这样的琐碎问题bootstrap就是这样的雷区。

您是否处理过类似的问题?

第4209篇《jQuery没有在bootstrap-sass中定义》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
村村 2020.05.28

步骤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")

看看@这个链接它有一个有效的示例,并提供了一个有关键入是否不包含示例的问题。我在该项目中使用了Angular的bootstrap和jquery,您也可以检查存储库。

在您的情况下,您需要添加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"

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

这应该工作。

更新

我继续使用我提到的步骤,仅使用Angular中的jquery创建了一个引导模式。

它起作用检查此gh页面链接-LINK

如果您要检查源代码是否相同,请检查LINK

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

神乐 2020.05.28

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

然后像以前一样将jQuery公开为变量。

十刃 2020.05.28

我没有专门在Angular 2中使用Bootstrap,但是我在Angular 1中使用,情况是一样的,因为常规版本的Bootstrap设计为可与jQuery一起使用,而并非为Angular构建的。您当然可以安装jQuery,但是Javascript可能无法在Angular的上下文中正常工作。

最简单的解决方案是使用考虑到Angular构建的版本,我相信ng-bootstrap是其中最突出的版本。我自己没有使用过,但是我为Angular 1使用了angular-ui-bootstrap,这似乎是同一项目的Angular 2对应版本。

另外,您也可以自己将其包装在指令中,但是如果您可以让ng-bootstrap做您想做的事,我会避免这样做,因为这样做会做更多的工作。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android