如何将Bootstrap JS和Jquery JS添加到Next JS
How to add Bootstrap JS and Jquery JS to Next JS
这是 运行 在 create-react-app 和 Next JS 上的应用程序
。它们之间的区别是 CRA 似乎已经加载了 bootstrap.mon.js 和 jquery.min.js 而 NextJS 没有。我通过 next/head 向 NextJS 代码添加了一个 HEAD 部分,并尝试加载这两个 JS 文件。虽然没有错误,但我也没有看到正确的结果。
有人能帮我理解为什么 NextJS 会发生这种情况,我应该怎么做才能让 NextJS 使用 bootstrap 和 jquery
正确加载我的应用程序
通过 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;
您必须在客户端要求模块。所以你可以使用这个
// _app.js
if (typeof window !== "undefined") {
require("jquery");
require("popper.js");
require("bootstrap/dist/js/bootstrap");
}
将此代码段添加到您的 _app.js 中,就在您的 return 代码上方
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
这是 运行 在 create-react-app
通过 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;
您必须在客户端要求模块。所以你可以使用这个
// _app.js
if (typeof window !== "undefined") {
require("jquery");
require("popper.js");
require("bootstrap/dist/js/bootstrap");
}
将此代码段添加到您的 _app.js 中,就在您的 return 代码上方
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