【问题标题】:ProvidePlugin not working with jquery - webpackProvidePlugin 不适用于 jquery - webpack
【发布时间】:2018-02-04 13:41:24
【问题描述】:

我正在尝试在我的应用程序中访问 jquery 根据 webpack 网站上的信息,您可以使用 webpack 创建全局变量 https://webpack.js.org/plugins/provide-plugin/

这是我的 webpack 设置

module.exports = {
    entry: {
        index: "./scripts/index.js",
        vendorJS: ["jquery", "jquery-validation", "jquery-validation-unobtrusive"]
    }
    ,
    output: {
        path: path.join(__dirname, '/wwwroot/'),
        filename: '[name].js'
    },
    resolve: {
        extensions: ['.js', '.jsx', '.css', '.scss', '.sass']
    },
    module: {
        rules: [
            {
                test: /\.scss$/i,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: ['css-loader', 'sass-loader']
                })
            },
            {
                test: /\.css$/i,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: ['css-loader']
                })
            },
            {
                test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                use: ['url-loader?limit=10000&mimetype=application/font-woff&name=/fonts/[name].[ext]'],
            },
            {
                test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                use: ['file-loader?name=/fonts/[name].[ext]'],
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin(['./wwwroot']),
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            "window.jQuery": "jquery"
        }),
        css
    ],

}

使用 thius 设置我无法在控制台菜单中访问我的 $ - jquery。

知道为什么会这样吗?

【问题讨论】:

    标签: webpack webpack-2


    【解决方案1】:

    我知道现在已经很晚了,但对于 Google 员工(如果您关心隐私,或者 Duck Duck 爱好者),我遇到了同样的问题:

    如果我使用$: 'jquery' 它会抛出

    无法解析“jquery”

    如果我用过

    const jquery = require('jquery');
    $: jquery
    

    扔了

    无法导入模块“未定义”

    这终于对我有用了

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

    【讨论】:

    • 仅供参考,这对我不起作用。还是得到'$' is not defined
    • 这最终是由于需要定义 window.jQuery 的第 3 方插件。所以添加window.jQuery: 'jquery' 解决了我的问题。
    • 很高兴听到这个消息! :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 2014-08-10
    • 2018-09-03
    • 2018-05-21
    • 1970-01-01
    相关资源
    最近更新 更多