1

I have this error on frontend:

Uncaught ReferenceError: $ is not defined

This is after I have tried bundling all js files (including jQuery) in a folder into 1 file with:

var glob = require("glob");

module.exports = {
    entry: {
        bundle:  glob.sync("./src/js/*.js")
    },
    output: {
        filename: "[name].js",
        path: path.resolve(__dirname, "dist/js")
    },

There is no error when building.

Does bundling jQuery need some sort of unique approach?

Or if this relates to the "order" of the files bundled, I thought webpack was able to overcome this by design?

Edit:

I abandoned this approach of using glob, instead opting to go for a single entry file that has import statements for third party js libraries and jQuery plugins, eg:

entry_file.js:

import hljs from './highlight';

import $ from './jquery';

webpack.config.js:

module.exports = {
    entry: "./src/js/entry_file.js",
    output: {
        filename: "bundle.js",
        path: path.resolve(__dirname, "dist/js")
    },

This new approach is not without its own headaches, however, as some plugins/libraries have their own idiosyncrasies and throw errors like Uncaught ReferenceError: jQuery is not defined etc.

user1063287
  • 10,265
  • 25
  • 122
  • 218

2 Answers2

1

I ended up doing this:

In webpack.config.js:

At the top of the file:

var webpack = require("webpack");

in the plugins property:

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

and not importing jQuery in entry_file.js.

This approach was inspired by the second point in this answer:

https://stackoverflow.com/a/28989476

user1063287
  • 10,265
  • 25
  • 122
  • 218
-1

In your webpack.config.js you have to require the webpack

var path = require('path');
var webpack = require("webpack");

module.exports = {
    entry: './src/js/app.js',
    devtool: 'source-map',
    mode: 'development',
    output: {
        path: path.resolve(__dirname, 'dist/js'),
        filename: 'main.min.js'
    }
};

Hope this helps.

if you are building a package or a library for client use on the browser you might want to add a loader such as to compiled all assets.

module.exports = {
    entry: './src/js/app.js',
    devtool: 'source-map',
    mode: 'development',
    output: {
        path: path.resolve(__dirname, 'dist/js'),
        filename: 'main.min.js'
    },
    loaders: [
        {test: /\.js$/, loader:'buble'}
    ]
};
Codedreamer
  • 1,552
  • 15
  • 13