如何在webpack中导入jquery [英] How to import jquery in webpack

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

问题描述

当我在webpack上使用它时,我遇到了jquery的问题。
我的代码:

I have a problem with jquery when i using it on webpack. My code:

const path = require('path');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const CompressionPlugin = require("compression-webpack-plugin");

module.exports = {
    entry: {
        vendor: [
            './src/main/webapp/js/vendor/jquery-3.3.1.min.js',
            // './src/main/webapp/js/vendor/fs.js',
            './src/main/webapp/js/vendor/google-adsense.js',
            './src/main/webapp/js/vendor/jquery.menu-aim.min.js',
            './src/main/webapp/js/vendor/jquery.touchSwipe.min.js',
        ],
        app: './src/main/assets/js/desktop/app.js',
        mobile: './src/main/assets/js/mobile/app.js',
        touch: './src/main/assets/js/touch/app.js',
    },
    module: {
        rules: [{
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            },
            {
                test: require.resolve('jquery'),
                loader: 'expose-loader?jQuery!expose-loader?$'
            }
        ],
    },
    plugins: [
        // new CleanWebpackPlugin(['src/main/webapp/assets']),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'common' // Specify the common bundle's name.
        }),
        new UglifyJsPlugin({
            test: /\.js$/,
            sourceMap: process.env.NODE_ENV === "development"
        }),
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        })
    ],
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, './src/main/webapp/js')
    }
};

当上面的代码编译时,控制台抛出此错误

When above code compiles , console throws this error

vendor.js:1未捕获的ReferenceError:webpackJsonp未定义
在vendor.js:1

当我尝试使用这个

externals: {
  jquery: 'jQuery'
}

抛出

vendor.js:1 Uncaught ReferenceError: jQuery is not defined
    at Object.231 (vendor.js:1)
    at o (common.js:1)
    at Object.228 (vendor.js:1)
    at o (common.js:1)
    at window.webpackJsonp (common.js:1)
    at vendor.js:1

我在我的核心js文件中使用jquery 从'jquery'中导入$
我做错了什么?任何帮助?谢谢。

And i using jquery in my core js file import $ from 'jquery'. What did i do wrong ? any help ? Thank you.

推荐答案

所以 webpack.config.js 中的主题很少,其中一些冲突。只是列出它们以便我能更好地理解我认为你想要实现的目标。

So there are few themes in your webpack.config.js, some of which conflict. Just going to list them so I can better understand what I think you are trying to achieve.

主题1

您有一个名为 vendor 的条目,它明确引用了您可能已下载并放置在指定目录中的缩小的jQuery库。

You have an entry called vendor that is clearly referencing a minified jQuery library you have presumably downloaded and placed in the directory specified.

主题2

您还有 expose-loader 这对于中可能列出的 node_modules 中的 jquery 库是必不可少的你的 package.json 的依赖

You also have an expose-loader that is essential exposing the jquery library from its node_modules probably listed in the dependencies of your package.json.

这使 jquery node_modules 中可用 $ jQuery

在包含您的捆绑包的网页的全球范围内。

This makes the jquery in the node_modules available as $ and jQuery in the global scope of the page where your bundle is included.

主题3

您还包含了 ProvidePlugin 以及jQuery的配置。

You also have included the ProvidePlugin with configuration for jQuery.

ProvidePlugin 应该将依赖项注入模块代码的范围,这意味着你不需要从'jquery'中输入 import $而不是 $ jQuery 已经可以在所有模块中使用。

The ProvidePlugin is supposed to inject dependencies into the scope of your module code, meaning you do not need to have import $ from 'jquery' instead $ and jQuery will already be available in all of your modules.

结论

从我收集到的内容 我认为 你试图从静态文件中捆绑jQuery供应商包中的 ./ src / main / webapp / js / vendor / jquery-3.3.1.min.js

然后,您尝试将供应商包中的库公开给全局范围(jQuery)。

You are then trying to expose the libraries in the vendor bundle to the global scope (jQuery).

然后还让您的应用程序代码能够从中导入jQuery全球范围内供应商捆绑包提供的内容。

Then also have your application code able to import jQuery from what is made available by the vendor bundle in the global scope.

回答

所以,如果你正在做的事情,你需要做以下事情。

So if that is what you are doing you need to do the following things.

首先,检查你的 package.json 文件依赖 > jquery的。如果你想删除它,如果你打算使用你的 jquery-3.3.1.min.js 文件来提供jQuery,则不需要它您的申请。

Firstly, check in your package.json files dependencies for jquery. If its there you want to remove it, there's no need for it if you're going to use your jquery-3.3.1.min.js file instead to provide jQuery to your application.

其次,更改 expose-loader 测试 c $ c>在您的条目中看到 jquery-3.3.1.min.js 文件时触发,而不是从 jquery <解析它/ code>依赖于 node_modules

Secondly, change your test of the expose-loader to trigger when it sees your jquery-3.3.1.min.js file in your entries, not resolve it from the jquery dependency from your node_modules.

这个正则表达式模式应该可以解决问题。

This regex pattern should do the trick.

{
  test: /jquery.+\.js$/,
  use: [{
      loader: 'expose-loader',
      options: 'jQuery'
  },{
      loader: 'expose-loader',
      options: '$'
  }]
}

第三,删除 ProvidePlugin 如果您要使用从$ jquery'明确导入库,则不需要它。

Thirdly, remove the ProvidePlugin if you're going to import the library explicitly with import $ from 'jquery' you do not need it.

最后,你需要告诉webpack wh它会看到 jquery 的导入,它可以从全局范围内的 window.jQuery 解决此问题。您可以使用已经引用的外部配置来执行此操作。

Lastly, you need to tell webpack when it sees an import for jquery it can resolve this from window.jQuery in the global scope. You can do this with the externals configuration you already referenced.

externals: {
  jquery: 'jQuery'
}

通过所有这些更改,您最终应该使用 webpack。 config.js 看起来像这样的文件。

With all these changes you should end up with a webpack.config.js file that looks like this.

const path = require('path');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const CompressionPlugin = require("compression-webpack-plugin");

module.exports = {
    entry: {
        vendor: [
            './src/main/webapp/js/vendor/jquery-3.3.1.min.js',
            // './src/main/webapp/js/vendor/fs.js',
            './src/main/webapp/js/vendor/google-adsense.js',
            './src/main/webapp/js/vendor/jquery.menu-aim.min.js',
            './src/main/webapp/js/vendor/jquery.touchSwipe.min.js',
        ],
        app: './src/main/assets/js/desktop/app.js',
        mobile: './src/main/assets/js/mobile/app.js',
        touch: './src/main/assets/js/touch/app.js',
    },
    module: {
        rules: [{
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            },
            {
                test: /jquery.+\.js$/,
                use: [{
                    loader: 'expose-loader',
                    options: 'jQuery'
                },{
                    loader: 'expose-loader',
                    options: '$'
                }]
            }
        ],
    },
    plugins: [
        // new CleanWebpackPlugin(['src/main/webapp/assets']),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'common' // Specify the common bundle's name.
        }),
        new UglifyJsPlugin({
            test: /\.js$/,
            sourceMap: process.env.NODE_ENV === "development"
        })
    ],
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, './src/main/webapp/js')
    },
    externals: {
        jquery: 'jQuery'
    }
};

我希望这不仅可以给你答案,而且可以解释你出错的地方。

I hope that does not just give you the answer but enough explanation as to where you were going wrong.

这篇关于如何在webpack中导入jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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