ReactJS构建报错:无法解析‘jquery’依赖问题求助
Hey there, let's work through this issue—even though you've installed jQuery via npm, webpack is having trouble locating it during your build. Here are a few actionable steps to fix this:
1. Reinstall jQuery to Fix Potential Corruption
Sometimes the node_modules folder can have missing or corrupted files. Let's do a clean reinstall of the exact jQuery version you need:
npm uninstall jquery npm install jquery@1.9.1 --save
This ensures you get a fresh, intact installation of jQuery 1.9.1 linked properly to your project.
2. Adjust Your jQuery Import/Require Statement
In your index.js, try switching to an ES6 import instead of require()—webpack handles ES6 imports more reliably for module resolution. You can still assign jQuery to the global scope so Bootstrap can access it:
import React from 'react'; import ReactDOM from 'react-dom'; import App from './app'; import $ from 'jquery'; // Use ES6 import here global.jQuery = $; global.$ = $; // Optional, if you need the $ alias globally too require('bootstrap'); require('bootstrap/dist/css/bootstrap.min.css'); require('bootstrap/dist/css/bootstrap-theme.min.css'); ReactDOM.render(<App view="DemoApp" />, document.getElementById('root'));
3. Advanced: Use Webpack's ProvidePlugin (No Eject Needed)
If the above steps don't work, you can use react-app-rewired to tweak your webpack config without ejecting Create React App:
- First install the tool:
npm install react-app-rewired --save-dev - Create a
config-overrides.jsfile in your project root:const webpack = require('webpack'); module.exports = function override(config, env) { config.plugins.push( new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }) ); return config; }; - Update your
package.jsonscripts to usereact-app-rewired:"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test --env=jsdom", "eject": "react-scripts eject" }
This tells webpack to automatically inject jQuery wherever $ or jQuery is referenced, eliminating the module resolution error.
After trying these steps, run npm run build again. The error should be resolved if it was related to installation, import syntax, or webpack's module lookup.
内容的提问来源于stack exchange,提问作者Karthikeyan

