如何将Bootstrap JS和Jquery JS添加到Next JS

7
这是一个运行在 create-react-appenter image description hereNextJSenter image description here上的应用程序。它们之间的区别是,CRA似乎已加载了bootstrap.mon.js和jquery.min.js,而NextJS没有。我通过next/head为NextJS代码添加了HEAD部分,并尝试加载这两个JS文件。虽然没有错误,但我也没有看到正确的结果。能否有人帮我理解为什么会发生这种情况,并告诉我如何让NextJS正确加载我的应用程序与bootstrap和jquery?

CRA的代码 - https://github.com/KrishnanSriram/cra NextJS的代码 - https://github.com/KrishnanSriram/nextjs - Krishnan Sriram
请告诉我如果您找到了解决方案。 - Yorkshireman
4个回答

3
将此片段添加到您的_app.js文件中,就在您的返回代码上方。
useEffect(() => {
import("bootstrap/dist/js/bootstrap");
  }, []);

那么你的完整_app.js应该如下所示:

import { useEffect } from 'react';

function MyApp({ Component, pageProps }: AppProps) {
  useEffect(() => {
    import("bootstrap/dist/js/bootstrap");
  }, []);

  return <Component {...pageProps} />
}

export default MyApp

对我来说不起作用,因为它显示模块未找到:无法解析“js/whatevermyjsis.js”。 - afikri

1

你需要在客户端要求模块,这样才能使用此功能。

// _app.js

if (typeof window !== "undefined") {
  require("jquery");
  require("popper.js");
  require("bootstrap/dist/js/bootstrap");
}

0

在 Bootstrap 的 Script 标签中使用 defer 属性,这将有助于先加载 jQuery,然后再加载 Bootstrap。

      <Script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.2/jquery.min.js" strategy="afterInteractive" ></Script>
  <Script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" crossOrigin="anonymous" strategy="lazyOnload" defer/>

0

在通过npm安装后,您可以在componentDidMount()中要求客户端库。

import React, { Component } from 'react';

export class HomePage extends Component {
    render() {
        return (
            <div>
                Hello
            </div>
        );
    }

    componentDidMount() {
        require('jquery');
        require('popper');
        require('bootstrap');
    }
}

export default HomePage;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接