代码之家  ›  专栏  ›  技术社区  ›  Matt Anxo P

使用webpack的provideplugin时,jquery不可用作“$”

  •  0
  • Matt Anxo P  · 技术社区  · 6 年前

    我试图使用jquery作为 $ 在我的webpack应用程序条目中 index.js 在浏览器中运行应用程序时收到此错误:

    uncaught typeerror:无法读取未定义的属性“fn”

    这是因为我要导入的模块中有一行调用 bootstrap-switch ,问题是:

    $.fn.bootstrapSwitch = function() {

    所以我没有 $ 作为全局变量工作。我按照指示 ProvidePlugin docs ,如下所示。我也试过了 this question 但那没用。

    这是我的 webpack.config.js 文件:

    module.exports = {
        entry: {
            main: './src/index.js'
        },
        plugins: {
            new webpack.ProvidePlugin({
                $: 'jquery',
                jQuery: 'jquery'
            })
        }
    }
    

    这是我的 src/index.js 文件:

    import 'bootstrap-switch';
    
    console.log('I am running');
    

    任何帮助都将不胜感激。

    编辑

    此问题的前一个版本询问了一个实际上是eslint错误的生成错误。感谢@ujint34帮助我解决了这个问题,并将注意力集中在上面列出的实际错误上。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Ito Pizarro    6 年前

    我添加这个作为未来用户的答案。

    尝试添加 'window.jQuery': 'jquery' 给你的 webpack.ProvidePlugin() 设置。

    module.exports = {
        ...
        plugins: [
            new webpack.ProvidePlugin( {
                $: 'jquery',
                jQuery: 'jquery',
                'window.jQuery': 'jquery'
            } )
        ]
    };
    
        2
  •  2
  •   UjinT34    6 年前

    no-undef 是eslint错误。它不知道你的网页包设置。你可以 specify global variables in esling config :

    {
        "globals": {
            "$": "readonly",
            "jQuery": "readonly"
        }
    }