【问题标题】:Error when trying to use Kendo UI with AngularJS and Webpack尝试将 Kendo UI 与 AngularJS 和 Webpack 一起使用时出错
【发布时间】:2017-03-23 09:07:15
【问题描述】:

我知道以前有人问过这个问题,但我似乎无法弄清楚。

我有一个非常简单的项目设置,我想将 Kendo UI 与 AngularJS 一起使用,并将其与 Webpack 捆绑在一起。

代码如下:

app.js

import * as $ from 'jquery';
import 'angular';
import 'kendo-ui-core';

var app = angular.module('app', ['kendo.directives']);

index.html

<html lang="en">
    <head>
        <meta charset="utf-8">
    </head>
    <body ng-app="app">
        <input kendo-date-picker />

        <script src="bundle.js"></script>
    </body>
</html>

webpack.config.js

var webpack = require('webpack');

module.exports = {
    entry: "./app.js",
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
    module: {
        loaders: [
            { test: /\.css$/, loader: "style!css" }
        ]
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            'window.jQuery': "jquery"
        })
    ]
};

但是当我运行应用程序时,我收到以下错误消息:

The Kendo UI directives require jQuery to be available before AngularJS. 
Please include jquery before angular in the document.

我不确定这里的问题是什么..有人吗?

【问题讨论】:

    标签: angularjs kendo-ui webpack


    【解决方案1】:

    产生此错误的断言是(来自 Kendo UI):

    if (!(element instanceof jQuery)) {
        throw new Error("The Kendo UI directives require...");
    }
    

    如果您在该行设置断点并将 element.constructorjQuery 进行比较,它们将是不同的实例,因此 webpack 可能不止一次加载 jQuery(可能会查看不同的文件夹)。

    要解决这个问题,您可以将 resolve option 添加到您的 webpack 配置中,将路径传递给您的 node_modules 文件夹,以便它只会在那里搜索模块:

    resolve: {
        modules: [__dirname + '/node_modules']
    },
    

    【讨论】:

    • Samir:感谢 Kendo 使用不同的 jQuery 副本的洞察力!
    【解决方案2】:

    当前版本的 kendo-ui-core (2017.3.1116) 配置了对 jquery 小于 3.0.0 的依赖。如果您的项目使用的 jquery 版本高于此 npm,则会在其自己的 node_module 子文件夹中为 kendo-ui-core 提供其自己的私有 jquery 版本。默认的 webpack 配置将导致 kendo-ui-core 中对 jquery 的任何引用解析为这个私有版本。

    Samir 的解决方案有效地改变了 Webpack 将搜索依赖项的位置以排除任何私有 node_module 文件夹。这可能适合您的情况,但您应该记住,其他模块可能需要它们自己的某些依赖项的私有版本。

    另一种解决方案是使用 jquery 的别名来强制依赖它的每个模块使用相同的副本。你这样做:

     resolve: {
        alias: {
            jquery: path.resolve(__dirname, "node_modules/jquery"), 
        },
        modules: ["node_modules"]
     }
    

    【讨论】:

      【解决方案3】:

      听起来像是加载顺序问题。您需要 jQuery 在 angular 之前可用。

      尝试首先使用脚本标签加载 jquery,而不是将其与您的 src 代码捆绑到 bundle.js 中。类似的东西

      <script src="jquery.js></script>
      <script src="bundle.js"></script>
      

      【讨论】:

      • 确实有效,但这并不能回答我的问题。在 app.js 中,我想将所有依赖项导入 app.js 中,而不是将它们放在单独的脚本标签中
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 2015-07-03
      相关资源
      最近更新 更多