'jQuery is not defined in NEXT JS application
I have two separate projects, Both contain the same package.json dependencies. Now the issue which I am facing is in one project the below script is working fine:
<Script id="show-banner" strategy="afterInteractive">
{`jQuery(function() { scrollinit("carousel", 3, 1, true, true, true, true, false);})`}
</Script>
While in the other project I am facing this error:
what could be the possible solution for that as I have tried few solutions but they never worked and I am new to next js
This is what browser embed for both the projects:
next.config.js for jQuery not running is :
/** @type {import('next').NextConfig} */
const isProd = process.env.NODE_ENV === 'production';
const { i18n } = require('./next-i18next.config');
const fs = require('fs');
const http = require('http');
module.exports = {
// allows you the rewriting of URLs
i18n,
// allows you to set headers for certain requests
async headers() { return []; },
pageExtensions: ['mdx', 'md', 'jsx', 'js', 'tsx', 'ts'],
reactStrictMode: true,
eslint: {
dirs: ['components', 'containers', 'core', 'pages', 'redux', 'shared', 'sockets', 'utils']
},
env: {
pubnub: {
publishKey: 'publishKey',
subscribeKey: 'subscribeKey',
uuid: 'UUID',
channels: {}
},
api: {
baseUrl: '{mybaseurl}',
configurationUrl: () => this.env.api.baseUrl + 'clients/config'
},
},
basePath: '',
assetPrefix: isProd ? '' : '',
poweredByHeader: false,
images: {
domains: ['3qqk4c7swve3mhkbo1xpvbtm-wpengine.netdna-ssl.com', 'vepimg.b8cdn.com', 'vepimg1.b8cdn.com', 'images.unsplash.com']
}
};
_app.js for which jQuery is not running is below:
import type { AppProps } from 'next/app';
// import App from 'next/app';
// import { PubNubProvider } from 'pubnub-react';
import '../public/styles/globals.css';
import { NextPage } from 'next';
import { ReactElement, ReactNode, useEffect } from 'react';
import { Provider } from 'react-redux';
// import { useSocketTransport } from '../shared/hooks/socket-transport.hook';
import rootStore from '../redux/store';
import { PersistGate } from 'redux-persist/lib/integration/react';
import Router, { useRouter } from 'next/router';
import { WEB_VITAL_LABEL } from '../shared/constants/webvitals.constants';
import { customVitalsHandler, webVitalsHandler } from '../shared/utils/vitals.utils';
import { IWebVital } from '../shared/models/webvital.model';
// import { useUserStory } from '../shared/hooks/userstory.hook';
import { config } from '../core/configs/dev-config';
import { consoleLogUtils } from '../shared/utils/console-log.utils';
import ServerAPI from '../core/api/server.API';
import { appWithTranslation } from 'next-i18next';
import nextI18NextConfig from '../next-i18next.config.js';
import { commonUtils } from '../shared/utils/commons.utils';
import '../shared/extensions';
import Wrapper from '../components/layout/default/wrapper.component';
import { isMobile } from 'react-device-detect';
Router.events.on('routeChangeStart', (url: string) => {
// debugger;
});
const { store, persistor } = rootStore();
type NextPageWithLayout = NextPage & {
getLayout?: (page: ReactElement) => ReactNode;
}
type AppPropsWithLayout = AppProps & {
Component: NextPageWithLayout;
props: any;
apiResult: any;
environmentVariables: any;
isLocalhost: boolean;
}
export function reportWebVitals(metric: IWebVital) {
metric.label && metric.label === WEB_VITAL_LABEL ? webVitalsHandler(metric) : customVitalsHandler(metric);
}
function MyApp({ Component, environmentVariables, pageProps, apiResult, isLocalhost }: AppPropsWithLayout) {
// const { getSocketInstance, stopSocketTransport } = useSocketTransport();
// const socketInstance = getSocketInstance();
// const { initUserStory } = useUserStory();
const router = useRouter();
useEffect(() => {
if (!config.api.isEndpointLoaded && apiResult) {
config.api.configJson = apiResult;
config.api.isLocalhost = isLocalhost;
config.api.isEndpointLoaded = true;
config.defaultLanguage = apiResult.languages.default;
config.availableLanguages = commonUtils.convertStringToArray(apiResult.languages.options) ?? [];
}
if (environmentVariables) {
config.envVariables = environmentVariables;
}
// initUserStory();
// return () => stopSocketTransport();
});
// get Layout of page if defined, otherwise fallback to Normal Layout
// eslint-disable-next-line arrow-body-style
const getLayoutFn = () => {
return Component.getLayout
? Component.getLayout(<Component {...pageProps} />)
: Component;
};
return (
<>
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
{/* <PubNubProvider client={socketInstance}> */}
{/* Layout is added here for consistent Layout across pages */}
<div className="main">
{!isMobile && <Wrapper>
<Component {...pageProps} />
</Wrapper>}
{isMobile && <Component {...pageProps} />}
</div>
{/* {getLayoutFn()} */}
{/* </PubNubProvider> */}
</PersistGate>
</Provider>
</>
);
}
let isApplicationLoaded = false;
// Method to get Serverside Api URL Configuration
MyApp.getInitialProps = async ({ Component, ctx }: any) => {
// process.env.newvariable = 'Done!!!';
if (ctx && ctx.req) {
// added a dummy commit
const processKeys = { ...process.env };
let { host } = ctx.req.headers;
let pageProps = {};
// [Todo: Remove] This code needs to be removed
let isLocalhost = false;
if (!host || host.indexOf('localhost') > -1) {
isLocalhost = true;
}
host = 'jovenesmercosur2021.com'; // 'semex.vfairs.com';
// }
// const configurationUrl = config.api.configurationUrl(host);
const serverApi = new ServerAPI();
const apiResult = await serverApi.getServerApiUrl(host);
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
if (ctx.res && !isApplicationLoaded && apiResult.languages.default !== 'en') {
isApplicationLoaded = true;
ctx?.res?.writeHead(307, { Location: '/' + apiResult.languages.default + ctx.req.url });
ctx?.res?.end();
}
return { environmentVariables: processKeys, pageProps, apiResult, isLocalhost };
}
consoleLogUtils.coloredLog('Initial Props for Client side');
return { pageProps: {} };
};
export default appWithTranslation(MyApp, nextI18NextConfig);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
