首页 文章

管理webpack中的jQuery插件依赖项

提问于
浏览
366

我在我的应用程序中使用Webpack,在其中我创建了两个入口点 - 所有JavaScript文件/代码的bundle.js,以及jQuery和React等所有库的vendors.js . 我该怎么做才能使用jQuery作为依赖项的插件,我想在vendors.js中也有它们?如果这些插件有多个依赖项怎么办?

目前我正在尝试使用这个jQuery插件 - https://github.com/mbklein/jquery-elastic . Webpack文档提到providePlugin和imports-loader . 我使用了providePlugin,但jQuery对象仍然不可用 . 以下是我的webpack.config.js的样子 -

var webpack = require('webpack');
var bower_dir = __dirname + '/bower_components';
var node_dir = __dirname + '/node_modules';
var lib_dir = __dirname + '/public/js/libs';

var config = {
    addVendor: function (name, path) {
        this.resolve.alias[name] = path;
        this.module.noParse.push(new RegExp(path));
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jquery: "jQuery",
            "window.jQuery": "jquery"
        }),
        new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js', Infinity)
    ],
    entry: {
        app: ['./public/js/main.js'],
        vendors: ['react','jquery']
    },
    resolve: {
        alias: {
            'jquery': node_dir + '/jquery/dist/jquery.js',
            'jquery.elastic': lib_dir + '/jquery.elastic.source.js'
        }
    },
    output: {
        path: './public/js',
        filename: 'bundle.js'
    },
    module: {
        loaders: [
            { test: /\.js$/, loader: 'jsx-loader' },
            { test: /\.jquery.elastic.js$/, loader: 'imports-loader' }
        ]
    }
};
config.addVendor('react', bower_dir + '/react/react.min.js');
config.addVendor('jquery', node_dir + '/jquery/dist/jquery.js');
config.addVendor('jquery.elastic', lib_dir +'/jquery.elastic.source.js');

module.exports = config;

但尽管如此,它仍然在浏览器控制台中引发错误:

未捕获的ReferenceError:未定义jQuery

同样,当我使用imports-loader时,它会抛出一个错误,

需求未定义'

在这一行:

var jQuery = require("jquery")

但是,当我不将它添加到我的vendors.js文件时,我可以使用相同的插件,而是以正常的AMD方式需要它,因为我如何包含我的其他JavaScript代码文件,如 -

define(
[
    'jquery',
    'react',
    '../../common-functions',
    '../../libs/jquery.elastic.source'
],function($,React,commonFunctions){
    $("#myInput").elastic() //It works

});

但这不是我想要做的,因为这意味着jquery.elastic.source.js与我在bundle.js中的JavaScript代码捆绑在一起,我希望我的所有jQuery插件都在vendors.js包中 . 那么我该如何实现这一目标呢?

11 回答

  • 10

    这适用于webpack.config.js

    new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
        }),
    

    在另一个javascript或HTML添加:

    global.jQuery = require('jquery');
    
  • 6

    将其添加到webpack.config.js中的plugins数组中

    new webpack.ProvidePlugin({
        'window.jQuery': 'jquery',
        'window.$': 'jquery',
    })
    

    然后通常需要jquery

    require('jquery');
    

    如果痛苦持续让其他脚本看到它,请尝试通过(在条目js中)将其显式放置在全局上下文中

    window.$ = jQuery;
    
  • 2

    我不知道我是否理解你想要做什么,但我不得不使用jQuery插件,需要jQuery在全局上下文(窗口)中,我将以下内容放在我的_390148中:

    var $ = require('jquery');
    window.jQuery = $;
    window.$ = $;
    

    我只需要在任何我想要的地方 jqueryplugin.min.jswindow.$ 按预期扩展插件 .

  • 51

    我发现的最佳解决方案是:

    https://github.com/angular/angular-cli/issues/5139#issuecomment-283634059

    基本上,你需要在typings.d.ts上包含一个虚拟变量,从你的代码中删除任何“import * as $ from jquery”,然后手动将标签添加到你的SPA html的jQuery脚本中 . 这样,webpack将不会妨碍您,并且您应该能够在所有脚本中访问相同的全局jQuery变量 .

  • 0

    In your webpack.config.js file add below:

    var webpack = require("webpack");
     plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        })
     ],
    

    Install jQuery using npm:

    $ npm i jquery --save
    

    In app.js file add below lines:

    import $ from 'jquery';
    window.jQuery = $;
    window.$ = $;
    

    这对我有用 . :)

  • 72

    对于jquery的全局访问,存在几个选项 . 在我最近的webpack项目中,我希望全局访问jquery,所以我在插件声明中添加了以下内容:

    plugins: [
        new webpack.ProvidePlugin({
          $: "jquery",
          jQuery: "jquery"
        })
      ]
    

    这意味着可以通过全局引用$和jQuery从JavaScript源代码中访问jquery .

    当然,您还需要通过npm安装jquery:

    $ npm i jquery --save
    

    有关此方法的工作示例,请随时将我的应用程序分叉到github

  • 2

    在使用Webpack 3.8.1及以下内容将 $jQuery 作为全局变量公开时,我得到了很好的工作 .

    将jQuery安装为项目依赖项 . 您可以省略 @3.2.1 以安装最新版本或指定其他版本 .

    npm install --save jquery@3.2.1
    

    如果尚未安装,请将 expose-loader 安装为开发依赖项 .

    npm install expose-loader --save-dev
    

    配置Webpack为我们加载和公开jQuery .

    // webpack.config.js
    const webpack = require('webpack')
    
    module.exports = {
      entry: [
        // entry bits
      ],
      output: {
        // output bits
      },
      module: {
        rules: [
          // any other rules
          {
            // Exposes jQuery for use outside Webpack build
            test: require.resolve('jquery'),
            use: [{
              loader: 'expose-loader',
              options: 'jQuery'
            },{
              loader: 'expose-loader',
              options: '$'
            }]
          }
        ]
      },
      plugins: [
        // Provides jQuery for other JS bundled with Webpack
        new webpack.ProvidePlugin({
          $: 'jquery',
          jQuery: 'jquery'
        })
      ]
    }
    
  • 5

    编辑:有时您希望将webpack简单地用作简单Web项目的模块捆绑器 - 以保持您自己的代码组织 . 以下解决方案适用于那些只希望外部库在模块中按预期工作的人 - 而不需要花费大量时间进入webpack设置 . (-1后编辑)

    快速简单(es6)解决方案,如果您仍在努力或想要避免外部配置/额外的webpack插件配置:

    <script src="cdn/jquery.js"></script>
    <script src="cdn/underscore.js"></script>
    <script src="etc.js"></script>
    <script src="bundle.js"></script>
    

    在模块内:

    const { jQuery: $, Underscore: _, etc } = window;
    
  • 15

    这适用于 webpack 3:

    在webpack.config.babel.js文件中:

    resolve: {
        alias: {
             jquery: "jquery/src/jquery"
        },
     ....
    }
    

    并使用 ProvidePlugin

    new webpack.ProvidePlugin({
            '$': 'jquery',
            'jQuery': 'jquery',
        })
    
  • 2

    我尝试了一些提供的答案,但似乎没有一个工作 . 然后我尝试了这个:

    new webpack.ProvidePlugin({
        'window.jQuery'    : 'jquery',
        'window.$'         : 'jquery',
        'jQuery'           : 'jquery',
        '$'                : 'jquery'
    });
    

    无论我使用哪个版本,似乎都可以工作

  • 681

    您已经混合了不同的方法来包含旧的供应商模块 . 这就是我要解决的问题:

    1.更喜欢未经宣传的CommonJS / AMD over dist

    大多数模块将 dist 版本链接到 package.jsonmain 字段中 . 虽然这对大多数开发人员都很有用,但对于webpack来说,最好为 src 版本添加别名,因为这样webpack能够更好地优化依赖关系(例如,当使用DedupePlugin时) .

    // webpack.config.js
    
    module.exports = {
        ...
        resolve: {
            alias: {
                jquery: "jquery/src/jquery"
            }
        }
    };
    

    但是,在大多数情况下, dist 版本也可以正常工作 .


    2.使用ProvidePlugin注入隐式全局变量

    大多数遗留模块依赖于特定全局变量的存在,例如 $jQuery 上的jQuery插件 . 在这种情况下,您可以配置webpack,以便在每次遇到全局 $ 时添加 var $ = require("jquery") 标识符 .

    var webpack = require("webpack");
    
        ...
    
        plugins: [
            new webpack.ProvidePlugin({
                $: "jquery",
                jQuery: "jquery"
            })
        ]
    

    3.使用imports-loader配置它

    一些遗留模块依赖 this 作为 window 对象 . 当模块在 this 等于 module.exports 的CommonJS上下文中执行时,这将成为一个问题 . 在这种情况下,您可以使用imports-loader覆盖 this .

    运行 npm i imports-loader --save-dev 然后

    module: {
        loaders: [
            {
                test: /[\/\\]node_modules[\/\\]some-module[\/\\]index\.js$/,
                loader: "imports-loader?this=>window"
            }
        ]
    }
    

    导入加载器也可用于手动注入各种变量 . 但是大部分时间 ProvidePlugin 在隐式全局变量时更有用 .


    4.使用imports-loader禁用AMD

    有些模块支持不同的模块样式,如AMD,CommonJS和legacy . 但是,大多数时候他们首先检查 define 然后使用一些古怪的代码来导出属性 . 在这些情况下,通过设置 define = false 可以帮助强制CommonJS路径 .

    module: {
        loaders: [
            {
                test: /[\/\\]node_modules[\/\\]some-module[\/\\]index\.js$/,
                loader: "imports-loader?define=>false"
            }
        ]
    }
    

    5.使用script-loader全局导入脚本

    如果您不关心全局变量并且只想使用旧脚本,那么您也可以使用脚本加载器 . 它在全局上下文中执行模块,就像您通过 <script> 标记包含它们一样 .


    6.使用noParse包含大型dists

    如果模块没有AMD / CommonJS版本且您想要包含 dist ,则可以将此模块标记为 noParse . 然后webpack将只包含模块而不解析它,这可以用来改善构建时间 . 这意味着需要AST的任何功能(如 ProvidePlugin )都不起作用 .

    module: {
        noParse: [
            /[\/\\]node_modules[\/\\]angular[\/\\]angular\.js$/
        ]
    }
    

相关问题