简体   繁体   中英

TypeError: webpack.ProvidePlugin is not a constructor

I'm trying to use a simple bootstrap, jquery plugin bootstrap-show-password but on load the page with form shows an error Uncaught ReferenceError: $ is not defined .

I don't understand why jquery wouldn't be loaded. I did the usual

npm install bootstrap jquery popper.js --save

and in my app.js I have

//import jQuery from "jquery";
//window.$ = window.jQuery = jQuery;
// this should be loaded with webpack, right?! ^

import "bootstrap";
import "bootstrap-show-password";

I'm looking at the webpack docs and it says to use the the plugin provider, but when I add that to my webpack.config.js

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

npm run build gives me TypeError: webpack.ProvidePlugin is not a constructor error

Did I miss something that needs to be installed?

Here are my package.json dependencies

  "devDependencies": {
    "@babel/preset-env": "^7.12.17",
    "autoprefixer": "^9.8.6",
    "babel-loader": "^8.2.2",
    "browser-sync": "^2.26.14",
    "eslint": "^7.20.0",
    "eslint-loader": "^4.0.2",
    "htmlnano": "^0.2.8",
    "imagemin-cli": "^6.0.0",
    "node-sass": "^5.0.0",
    "npm-run-all": "^4.1.5",
    "onchange": "^7.1.0",
    "postcss": "^8.2.6",
    "postcss-cli": "^8.3.1",
    "posthtml": "^0.15.1",
    "posthtml-cli": "^0.9.1",
    "posthtml-modules": "^0.7.3",
    "stylelint": "^13.11.0",
    "webpack": "^5.23.0",
    "webpack-cli": "^4.5.0"
  },
  "dependencies": {
    "bootstrap": "^4.6.0",
    "bootstrap-show-password": "^1.2.1",
    "jquery": "^3.5.1",
    "popper.js": "^1.16.1"
  }

OK, after a few hours I found that the culprit was incorrectly initialized webpack var in webpack.config.js . For reason that's beyond me I had there

const { webpack } = require("webpack");

instead of

const webpack = require("webpack");

Had the same issue and I was able to resolve it. This was my webpack config initially:

const { webpack } = require("webpack");

...
plugins: [
    ...
    new webpack.ProvidePlugin({
      Buffer: ["buffer", "Buffer"],
    }),
    ...
  ],
...

Here's what I did to resolve it:

// Import ProvidePlugin directly
const { webpack, ProvidePlugin } = require("webpack");

...
plugins: [
    ...
    // call the ProvidePlugin constructor directly
    new ProvidePlugin({
      Buffer: ["buffer", "Buffer"],
    }),
    ...
  ],
...

webpack.ProvidePlugin will only work if you used the default import of webpack like this,

const webpack = require("webpack");

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