Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to import Bootstrap on Next.JS but says "TypeError: Cannot read property 'jquery' of undefined"

I'm trying to import Bootstrap from a Next.js project. The order of my imports are:

import 'jquery';
import 'bootstrap';

I tried with another syntax...

require('jquery');
require('bootstrap');

But the result is the same...

TypeError: Cannot read property 'jquery' of undefined jQueryDetection /node_modules/bootstrap/dist/js/bootstrap.js:243:26

I inverted the position of the imports and don't work...

Im in index.js page, and... I have both packages installed

like image 979
Omar Ureña Avatar asked Feb 12 '20 23:02

Omar Ureña


1 Answers

The issue here is that your page is trying to import bootstrap whenever this page loads, including when the page is being rendered server-side by the Next.js server (or by the next export process). Bootstrap, though, can't run on the server-side because it looks for window.jquery as part of its startup process, and window is undefined when in the node env.

To fix this, you have to wrap the imports for bootstrap, jquery, and popper.js in a check to ensure they are only imported on the client-side:

// At the top of _app.tsx or your individual page:
if (typeof window !== "undefined") {
  require("jquery");
  require("popper.js");
  require("bootstrap");
}
like image 118
Zack Avatar answered Nov 03 '22 06:11

Zack