Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import jquery in webpack

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 Uncaught ReferenceError: webpackJsonp is not defined at vendor.js:1

And when i try to use this

externals: {
  jquery: 'jQuery'
}

It throws

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

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

like image 948
batgerel.e Avatar asked Feb 02 '18 09:02

batgerel.e


People also ask

Is not defined webpack jQuery?

"jQuery is not defined" or "$ is not defined"This error happens when your code (or some library that you are using) expects $ or jQuery to be a global variable. But, when you use Webpack and require('jquery') , no global variables are set.

What is provideplugin in webpack?

Automatically load modules instead of having to import or require them everywhere.

What is HTML webpack plugin?

This is a webpack plugin that simplifies creation of HTML files to serve your webpack bundles. This is especially useful for webpack bundles that include a hash in the filename which changes every compilation.

Why use jQuery?

The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.


1 Answers

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.

Theme 1

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

Theme 2

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.

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

Theme 3

You also have included the ProvidePlugin with configuration for 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.

Conclusion

From what I have gathered I think you're trying to bundle jQuery from the static file at ./src/main/webapp/js/vendor/jquery-3.3.1.min.js in a vendor bundle.

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

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

Answer

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

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.

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: '$'
  }]
}

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

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

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.

like image 157
Joshua Barnett Avatar answered Sep 30 '22 13:09

Joshua Barnett