文檔:https://nextjs.org/docs/getting-started
1 創(chuàng)建項(xiàng)目TS
yarn create next-app --typescript nextjs_demo
2. 配置項(xiàng)目
修改_app.tsx
烹俗, 各種Provider
都可以寫(xiě)在這里
import '../styles/globals.css'
import 'antd/dist/antd.css'
import type { AppProps } from 'next/app'
import { ThemeProvider } from 'styled-components'
function MyApp({ Component, pageProps }:AppProps) {
return <ThemeProvider theme={{
color:'red',
fontSize:'40px'
}}>
<Component {...pageProps} />
</ThemeProvider>
}
export default MyApp
3. next/image
的使用
<Image
src={'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fi2.hdslb.com%2Fbfs%2Farchive%2F3c90eb673244c95ff63bf3255230d1070a56a8e5.jpg&refer=http%3A%2F%2Fi2.hdslb.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1664009576&t=b38110e63b3bf95d420e63b9c9c81f53'}
width={800}
height={312}
placeholder="blur"
blurDataURL='data:image/jpeg;base64,/9j/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAIAAoDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAb/xAAhEAACAQMDBQAAAAAAAAAAAAABAgMABAUGIWEREiMxUf/EABUBAQEAAAAAAAAAAAAAAAAAAAMF/8QAGhEAAgIDAAAAAAAAAAAAAAAAAAECEgMRkf/aAAwDAQACEQMRAD8AltJagyeH0AthI5xdrLcNM91BF5pX2HaH9bcfaSXWGaRmknyJckliyjqTzSlT54b6bk+h0R//2Q=='
/>
4. 靜態(tài)資源放到public
文件夾下
5.getServerSideProps 和 getStaticProps 的區(qū)別
getStaticProps
:構(gòu)建時(shí)就會(huì)執(zhí)行衡蚂,服務(wù)器上運(yùn)行触徐,生成靜態(tài)HTML歌焦,每個(gè)人請(qǐng)求就會(huì)很快返回循衰,不會(huì)白屏
https://nextjs.org/docs/basic-features/data-fetching/get-static-props
- 純靜態(tài)頁(yè)面
- 頁(yè)面數(shù)據(jù)基本不變轧邪、許久變一次
export async function getStaticProps() {
const res = await fetch('https://.../posts')
const posts = await res.json()
return {
props: {
posts,
},
revalidate: 24*60*60, //1天更新一次 (單位秒)
}
}
getServerSideProps
:預(yù)渲染數(shù)據(jù),每次頁(yè)面請(qǐng)求都會(huì)執(zhí)行
https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props
- 預(yù)渲染數(shù)據(jù)拖吼,先請(qǐng)求一屏的數(shù)據(jù)緩存起來(lái)(看起來(lái)頁(yè)面加載快鼻疮、無(wú)白屏)
6.頁(yè)面動(dòng)態(tài)導(dǎo)入(取消服務(wù)器渲染,比如本地判斷window借嗽、isMobile等)
頁(yè)面中的各種組件也可以動(dòng)態(tài)導(dǎo)入(先顯示loading)
index.tsx
import dynamic from 'next/dynamic'
export default dynamic(
()=>import('./views/home'),
{
ssr:false,
loading:()=><></>
}
)
7. 安裝styled-components
yarn add babel-plugin-styled-components --dev
.babelrc
{
"presets": ["next/babel"],
"plugins": [
["styled-components", { "ssr": true, "displayName": true }],
[
"import",
{
"libraryName":"antd"
}
]
]
}
8.導(dǎo)入google字體态鳖,創(chuàng)建_document.tsx
import Document, { Html, Head, Main, NextScript } from "next/document";
class MyDocument extends Document {
static async getInitialProps(ctx:any) {
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps };
}
render() {
return (
<Html>
<Head>
<link
rel="stylesheet"
/>
<link
href="https://fonts.googleapis.com/css2?family=Roboto Condensed"
rel="stylesheet"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
9.部署服務(wù)器nginx
1. 部署到自己的服務(wù)器上(聯(lián)系后臺(tái)人員進(jìn)行配置)
http://www.shanhuxueyuan.com/news/detail/111.html
nextjs打包后的文件存儲(chǔ)在.next文件夾,但是只有這個(gè)文件夾下的內(nèi)容是不夠的恶导,因?yàn)橐趎ode端運(yùn)行浆竭,還需要next以及react及reactDom等,簡(jiǎn)單起見(jiàn)惨寿,我們可以把整個(gè)項(xiàng)目都傳到服務(wù)器邦泄。這樣的缺點(diǎn)就是node_modules比較大,不過(guò)這樣最簡(jiǎn)單裂垦。 在服務(wù)器端顺囊,進(jìn)入項(xiàng)目路徑 依次執(zhí)行 npm run build ,npm run start即可將項(xiàng)目運(yùn)行在服務(wù)器端蕉拢,默認(rèn)是localhost:3000特碳,我們肯定是要通過(guò)域名訪問(wèn)項(xiàng)目,因此還需要進(jìn)行域名配置晕换,可通過(guò)nginx反向代理來(lái)實(shí)現(xiàn)测萎。
server {
listen 80;
server_name yourdomain.com;
error_log /var/log/nginx/yourdomain_error.log;
location / {
proxy_pass
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
現(xiàn)在可以通過(guò)域名訪問(wèn)了,但是還是存在一個(gè)問(wèn)題届巩,就是我們剛才執(zhí)行的npm run start命令,必須打開(kāi)命令行才有效份乒,一旦關(guān)閉命令行恕汇,進(jìn)程也終止了,簡(jiǎn)單的做法就是通過(guò)nohup在后臺(tái)執(zhí)行 npm run start 或辖,這樣關(guān)閉命令行仍然有效瘾英。
nohup npm run start &
- PM2是node進(jìn)程管理工具,可以利用它來(lái)簡(jiǎn)化很多node應(yīng)用管理的繁瑣任務(wù)颂暇,如性能監(jiān)控缺谴、自動(dòng)重啟、負(fù)載均衡等耳鸯,而且使用非常簡(jiǎn)單
npm install -g pm2
為了簡(jiǎn)單的使用pm2湿蛔,我們先把項(xiàng)目下的package.json中添加一個(gè)server指令,server指令依次執(zhí)行next build和next start
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start",
"server":"next build && next start", //添加server指令
},
進(jìn)入到項(xiàng)目所在目錄
執(zhí)行如下命令
pm2 start npm --name yourName -- run server --watch
將yourName換成你的項(xiàng)目名县爬,這個(gè)是給這個(gè)進(jìn)程起的名稱阳啥,可以隨意
--watch代表監(jiān)聽(tīng)項(xiàng)目文件,當(dāng)文件發(fā)生變化是财喳,自動(dòng)重新加載如下指令察迟,這樣就很方便了斩狱,當(dāng)我們更改代碼之后,只需要傳到服務(wù)器即可扎瓶,pm2會(huì)自動(dòng)監(jiān)聽(tīng)所踊,重新執(zhí)行 npm run server
這樣就完成服務(wù)器部署了,可能有的同學(xué)還想服務(wù)器重啟之后自動(dòng)運(yùn)行這個(gè)命令概荷,使用pm2也很簡(jiǎn)單只需執(zhí)行如下命令即可
pm2 startup
2. 部署到vercel
上(最后的鏈接如此:https://nextjs-demo-self.vercel.app/)
- 將代碼
push
到自己的github
上
- 將代碼
- 2.打開(kāi)
https://vercel.com/dashboard
用自己的github
賬號(hào)登錄秕岛,選擇項(xiàng)目 - 如果自定義了輸出目錄這里也要改成一致
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
images: {
domains: ['gimg2.baidu.com'],
},
// distDir: 'build',
exportPathMap: async function (
defaultPathMap,
{ dev, dir, outDir, distDir, buildId }
) {
return {
'/': { page: '/' },
};
},
images: {
loader: 'akamai',
path:'',
}
}
- deploy