2

我在将velocity.js 集成到我现有的webpack 框架中并让它作为对jquery 的依赖项时遇到了极大的困难。

本质上,velocity.js 期望 jquery(或 $)在全局对象上可用,以便它可以增强功能,从而可以实现以下功能$(elem).velocity。我曾尝试使用“expose-loader”将两者都暴露jquery$窗口中,但遇到了错误global is not defined。以下是我的 webpack 配置的摘录

loaders: [
  { test: /\.coffee$/, loader: "coffee-loader" },
  { test: /\.less$/, loader: "style-loader!css-loader!less-loader" },
  { test: /\jquery\.min\.js/, loader: "expose?jQuery!expose?$" },
  { test: /\velocity\.min\.js/, loader: "expose?Velocity" }
]

我也尝试过使用非缩小版。这是加载jquery的错误所在:

module.exports = global["jQuery"] = require("-!/.../node_modules/expose-loader/index.js?$!/.../app/bower_components/jquery/dist/jquery.js");

/*****************
 ** WEBPACK FOOTER
 ** ./app/bower_components/jquery/dist/jquery.js
 ** module id = 6
 ** module chunks = 0
 **/

我不知道暴露加载器是如何工作的,也无法理解上述的意义,特别是因为我能够将velocity.js'暴露Velocity给全局窗口。

作为后备,我不得不var Velocity = require("velocity")进入我的应用程序文件并使用velocity.js,就像没有可用的jquery一样,即

Velocity(document.getElementById("rect"), { opacity: 0 }, { duration: 1000 })

任何帮助或建议将不胜感激。

4

1 回答 1

2

让这个工作有两个部分。首先像往常一样将 jQuery 加载到您的页面中。尝试将 jQuery 包含到您的 webpack 包中有点笨拙。

使用代码中的实际要求:

require("imports?$=jquery!<jQueryModule>")

替换<jQueryModule>为您要加载的模块的路径和/或名称。 Webpack将确保$为其正确映射,以便它可以作为插件附加。 jQueryModule可以只是您在webpack配置中定义别名的名称。就我个人而言,我更喜欢使用简单的名称而不是路径 - 这样您就可以管理搜索的文件夹上下文 - 但这是您的决定。

在您的webpack配置中,您想使用ProvidePlugin来告诉webpackjQuery可用:

 new webpack.ProvidePlugin({
    // Automtically detect jQuery and $ as free var in modules
    // and inject the jquery library
    // This is required by many jquery plugins
    $: "jquery",
    jQuery: "jquery",
    "window.jQuery": "jquery",
    "root.jQuery": "jquery"
 }),

当加载这种类型的代码时——你将变量导入到你正在使用的模块的命名空间中——而不是从模块中暴露一些东西——因此使用导入。

于 2015-08-28T06:12:51.920 回答