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
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
Share Improve this question edited Feb 14, 2020 at 14:46 MrCakes asked Feb 12, 2020 at 23:01 MrCakesMrCakes 1651 silver badge7 bronze badges 1- 1 I'm seeing this too. Will answer if I figure out a fix. EDIT: Got it - answering. – Zack Commented Apr 26, 2020 at 18:42
3 Answers
Reset to default 11The 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");
}
Sample _app.tsx based on @Zack 's answer but this one uses imports instead to have totally pliant code
// _app.tsx page
export default function MyApp({ Component, pageProps }) {
if (globalThis.window !== undefined) {
import("jquery").then(() => { import("bootstrap"); });
}
return <Component {...pageProps} />
}
I was also trying to fix this issue but instead I used react-bootstrap and it works fine