简体   繁体   English

如何使用Webpack包括jQuery和jQuery验证?

[英]How to include jQuery and jQuery Validation using Webpack?

I'm relatively new to Webpack and am trying to create a Universal React app using https://github.com/erikras/react-redux-universal-hot-example . 我是Webpack的新手,正在尝试使用https://github.com/erikras/react-redux-universal-hot-example创建一个Universal React应用。 I've included jQuery using: 我使用以下方法包含了jQuery:

var jquery = new webpack.ProvidePlugin({
  $: "jquery",
  jQuery: "jquery"
})

and including it in module.exports plugins array to make it global. 并将其包含在module.exports插件数组中以使其全局。 And in my JS file I am trying to include it like this 在我的JS文件中,我试图像这样包含它

import $ from 'jquery';
import jqueryValidation from 'jquery-validation';

However I am getting the following error in NodeJS: 但是我在NodeJS中收到以下错误:

> error given was: TypeError: $.extend is not a function  
[1]     at /Users/admin/repo/learnReact/node_modules/jquery-validation/dist/jquery.validate.js:19:3  
[1]     at /Users/admin/repo/learnReact/node_modules/jquery-validation/dist/jquery.validate.js:13:20  
[1]     at Object.<anonymous> (/Users/admin/repo/learnReact/node_modules/jquery-validation/dist/jquery.validate.js:17:2)  
[1]     at Module._compile (module.js:570:32)  
[1]     at Module._extensions..js (module.js:579:10)  
[1]     at require.extensions.(anonymous function) (/Users/admin/repo/learnReact/node_modules/babel-register/lib/node.js:152:7)  
[1]     at Object._module2.default._extensions.(anonymous function) [as .js] (/Users/admin/repo/learnReact/node_modules/require-hacker/babel-transpiled-modules/require hacker.js:260:68)  
[1]     at Module.load (module.js:487:32)  
[1]     at tryModuleLoad (module.js:446:12)  
[1]     at Module._load (module.js:438:3)  
[0] ./src/utils/validation.js

What am I doing wrong? 我究竟做错了什么? After a quick search online, I also tried expose-loader as suggested by some post, which also did not seem to work. 在线快速搜索后,我还尝试了一些帖子建议的Exposure-loader,但似乎也没有用。 Any help in fixing this or any reference to a good webpack tutorial will be highly appreciated. 修复此问题的任何帮助或对良好Webpack教程的任何引用将受到高度赞赏。

jquery can only be used on DOM. jQuery只能在DOM上使用。 so does validation 验证也是如此

https://www.npmjs.com/package/jquery#node

so if you want to include jquery you must inject it in your client entry file (webpack) using script tag 因此,如果要包含jquery,则必须使用脚本标记将其注入到客户端输入文件(webpack)中

this way jquery will always run in an environment with DOM. 这样,jquery将始终在具有DOM的环境中运行。 after that you will be able to use jquery through window.$ inside your react app. 之后,您将可以在react应用中通过window。$使用jquery。

(componentDidMount) (componentWillMount does not support DOM afaik)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM