jquerytwitter-bootstrap-3next.js

ReferenceError: jQuery is not defined Next.js


I'm using next js and using jquery, Bootstrap and few other js libraries.

This is my _app.js

import React from 'react';
import { Layout } from '../components';
import { Toaster } from 'react-hot-toast';
import Script from "next/script";

function MyApp({ Component, pageProps }) {

  return (
    <>
      <Script src="/js/jquery-2.1.1.min.js" type="text/javascript"></Script>
      <Script src="/js/bootstrap.min.js" type="text/javascript"></Script>
      <Script type="text/javascript" src="/js/jstree.min.js" ></Script>
      <Script type="text/javascript" src="/js/template.js" ></Script>
      <Script src="/js/common.js" type="text/javascript" ></Script>
      <Script src="/js/global.js" type="text/javascript" ></Script>
      <Script src="/js/owl.carousel.min.js" type="text/javascript" ></Script>
      <Layout>
        <Toaster />
        <Component {...pageProps} />
      </Layout>
    </>
  )
}

export default MyApp

But I'm getting this error,

Unhandled Runtime Error Error: Bootstrap's JavaScript requires jQuery

Call Stack /js/bootstrap.min.js (6:37)

But the funny thing is in inspect element in the browser the files are loaded. enter image description here

IS there any fix for this issue :(


Solution

  • Next.Js Script component loading strategy by default is after interactive but in your case jQuery need to load it first before interactive so your code will be somthing like this

    <Script src="assets/js/jquery-3.6.0.min.js" strategy="beforeInteractive"></Script>
    

    Ref: https://nextjs.org/docs/pages/api-reference/components/script