webpack无法解析"jquery" [英] webpack Can't resolve 'jquery'

查看:193
本文介绍了webpack无法解析"jquery"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Webpack的新手,目前我正在将该工具添加到我的项目中,在捆绑(webpack ...)依赖于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:

错误:无法在"C:\ some_folder"中解析"jquery"

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

我浏览了互联网上的类似帖子,但没有任何积极效果. 人们建议使用不同的方法,例如: -resolve.alias -插件ProvidePlugin

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

我使用的是webpack 3.3.0,在我的项目 jQuery 中,它是通过 script标签以常规方式加载的,在供应商捆绑包脚本之前. 包括jQuery在内的大多数供应商库都不在node_modules文件夹中.

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'
    };
};

最后一个条目jquery.placeholder.min.js有问题

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');

推荐答案

问题

由于jquery.placholder.min.js使用UMD作为其加载策略,因此它认识到它是通过require必需的-并尝试以相同的方式要求jQuery:

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看到require("jquery")并尝试捆绑jQuery库(node_modules中不存在).

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

解决方案是在webpack.config.js中将jQuery作为外部添加:

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"
  }
}

当模块标记为外部时,Webpack不会捆绑它,而是使用全局变量.

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

这篇关于webpack无法解析"jquery"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆