简体   繁体   中英

webpack Can't resolve 'jquery'

Hi I'm a new to Webpack , currently I'm adding this tool to my project, during bundling (webpack ...) jquery-dependent library I get an error like that:

Error: Can't resolve 'jquery' in 'C:\\some_folder'

I browsed through similar posts on internet with no positive effect. People recommend using different approaches like : - resolve.alias - plugins ProvidePlugin

I use webpack 3.3.0, in my project jQuery is loaded in normal way via script tag before vendor bundle scripts. Most of vendor librairies including jQuery live not in node_modules folder.

webpack.config.js:

const webpack = require('webpack');
const { resolve } = require('path');

module.exports = env => {
    return {
        context: resolve('src'),
        entry: {
            comp: './start.comp.js',
            culture: './start.culture.js',
            strategy: './start.strategy.js',
            vendors: './start.vendors.js'
        },
        output: {
            path: resolve('dist'),
            publicPath: '/dist/',
            filename: 'bundle.[name].js'
        },
        devtool: env.dev ? 'eval' : 'source-map'
    };
};

the last entry jquery.placeholder.min.js is a problem

require('./../assets/vendor/typeahead.js');
require('./../assets/vendor/hogan-2.0.0.js');
require('./../assets/vendor/swfobject.js');
require('expose-loader?_!./../assets/vendor/underscore-min.js');
require('expose-loader?FastClick!./../assets/vendor/fastclick.js');
require('expose-loader?AOS!./../assets/vendor/aos.js');
require('./../assets/vendor/jquery.placeholder.min.js');

Problem

Since jquery.placholder.min.js is using UMD as its loading strategy, it's recognizing that it is required via a require - and tries to require jQuery in the same way:

"object"==typeof module&&module.exports?require("jquery"):jQuery

Webpack sees require("jquery") and tries to bundle the jQuery library (which does not exist in the node_modules).

Solution

The solution is to add jQuery as an external in your webpack.config.js :

{
  ...
  externals: {
    // require("jquery") is external and available
    //  on the global var jQuery
    "jquery": "jQuery"
  }
}

When a module is marked as an external , Webpack knows not to bundle it, but instead use the global variable.

I was working in react i have found that when i import the react-bootstrap components sometimes the components come like {Buttons} from bootstarp ; then i got this error. But i solved it by calling the path from bootstrap to react-bootstrap ;

Check your auto import call and try changing it. this worked for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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