简体   繁体   中英

TypeError “Cannot read property 'jquery' of undefined” while using Webpack in Node.js app

Caveat: I am a current student so pretty fresh with all of this and it could very well be that I have applied a solution incorrectly. I have at least attempted to apply solutions that can be found at the following three links, but the same issue persists:

  1. https://github.com/webpack/webpack/issues/4258
  2. jQuery is not defined (using Webpack)
  3. https://webpack.js.org/loaders/expose-loader/

I have added import $ from "jquery"; to the top of my entry file, and here is the current state of my webpack.config file:

const path = require('path');
const webpack = require('webpack');
require('bootstrap');


module.exports = {
    module: {
        rules: [
            {
                test: require.resolve('jquery'),
                loader: 'expose-loader',
                options: {
                    exposes: {
                        globalName: "$",
                        override: true

                    },
                }
            }
        ],
    },

    // assigns root of bundle and beginning of dependency graph (default is ./src/index.js)
    entry: './assets/js/script.js',
    // webpack will bundle code at entry point and output into folder specified folder (default is ./dist/main.js)
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'main.bundle.js'
    },
    // default is 'production' mode, which will minify code automatically; in this case we do not want this feature
    plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
        }),
    ],
    mode: 'development'
};

Lastly, here is my package.json:

{
  "name": "food-festival",
  "version": "1.0.0",
  "description": "",
  "main": "assets/js/script.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "webpack": "webpack --watch",
    "build": "webpack"
  },
  "repository": {
    "type": "git",
    "url": ""
  },
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": ""
  },
  "homepage": "",
  "devDependencies": {
    "expose-loader": "^1.0.3",
    "webpack": "^5.15.0",
    "webpack-cli": "^4.3.1"
  },
  "dependencies": {
    "bootstrap": "^4.5.3",
    "jquery": "^3.5.1",
    "popper.js": "^1.16.1"
  }
}

After all that... I answered my own question. I had erroneously required bootstrap at the top of my webpack.config file, rather than my entry file. Facepalm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM