How to configure and use jQuery with webpack
11,787
You can use webpack.ProvidePlugin
to resolve the jQuery as a global identifier. When you use ProvidePlugin
you dont want to import jQuery
into the modules since it would be available as global variable.
something like
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]
Author by
modeller
Updated on June 17, 2022Comments
-
modeller almost 2 years
I have a very simple project to test run jQuery function with webpack. However I ran into errors at the bundle step. Here are the errors:
ERROR in ./~/jQuery/lib/node-jquery.js Module not found: Error: Cannot resolve module 'jsdom' in /home/mypc/IdeaProject/OpenDimSum/frontend/node_modules/jQuery/lib @ ./~/jQuery/lib/node-jquery.js 5:13-29 ERROR in ./~/jQuery/lib/node-jquery.js Module not found: Error: Cannot resolve module 'xmlhttprequest' in /home/mypc/IdeaProject/OpenDimSum/frontend/node_modules/jQuery/lib @ ./~/jQuery/lib/node-jquery.js 8:28-53 ERROR in ./~/jQuery/lib/node-jquery.js Module not found: Error: Cannot resolve module 'location' in /home/mypc/IdeaProject/OpenDimSum/frontend/node_modules/jQuery/lib @ ./~/jQuery/lib/node-jquery.js 13:24-43 ERROR in ./~/jQuery/lib/node-jquery.js Module not found: Error: Cannot resolve module 'navigator' in /home/mypc/IdeaProject/OpenDimSum/frontend/node_modules/jQuery/lib @ ./~/jQuery/lib/node-jquery.js 17:25-45
Here are my config files:
package.json{ "name": "frontend", "version": "1.0.0", "description": "", "main": "index.jsx", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "babel-core": "^6.17.0", "babel-loader": "^6.2.5", "babel-preset-es2015": "^6.16.0", "babel-preset-react": "^6.16.0", "jquery": "^2.2.2", "react": "file:node_modules/react", "react-dom": "file:node_modules/react-dom", "webpack": "^1.13.2", "webpack-dev-server": "^1.16.2" } }
webpack.config.js
var webpack = require('webpack') var path = require('path') var BUILD_DIR = path.resolve(__dirname, 'src/client/public'); var APP_DIR = path.resolve(__dirname, 'src/client/app'); var config = { entry: APP_DIR + '/index.jsx', output: { path: BUILD_DIR, filename: 'bundle.js', publicPath: 'public', }, module: { loaders: [ { test: /\.jsx?/, include: APP_DIR, loader: 'babel' }, { test: /\.css/, include: APP_DIR, } ] }, }; module.exports = config;
index.jsx:
import React from 'react' import {render} from 'react-dom' import $ from 'jQuery' (function () { $(document).ready(function() { console.log("It works!"); }); })();
If I install the mentioned modules (jsdom, xmlhttprequest, ..), the errors will be replaced by very long errors.
-
user1063287 almost 6 yearsIs it possible to add a third "line" to this, that says
jquery: "jquery"
? I am getting errorModule not found: Error: Can't resolve 'jquery'
, and I am wondering if it is because only$
andjQuery
are specified, and notjquery
with the lowercaseq
?