美文网首页already
next.js 初步开发到部署

next.js 初步开发到部署

作者: 精神病患者link常 | 来源:发表于2022-09-01 16:28 被阅读0次

    文档:https://nextjs.org/docs/getting-started

    1 创建项目TS

    yarn create next-app --typescript nextjs_demo

    2. 配置项目

    修改_app.tsx, 各种Provider都可以写在这里

    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. 静态资源放到public文件夹下

    image.png

    5.getServerSideProps 和 getStaticProps 的区别

    getStaticProps:构建时就会执行,服务器上运行,生成静态HTML,每个人请求就会很快返回,不会白屏
    https://nextjs.org/docs/basic-features/data-fetching/get-static-props

    1. 纯静态页面
    2. 页面数据基本不变、许久变一次
    export async function getStaticProps() {
      const res = await fetch('https://.../posts')
      const posts = await res.json()
      return {
        props: {
          posts,
        },
        revalidate: 24*60*60,  //1天更新一次 (单位秒)
      }
    }
    

    getServerSideProps:预渲染数据,每次页面请求都会执行
    https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props

    1. 预渲染数据,先请求一屏的数据缓存起来(看起来页面加载快、无白屏)

    6.页面动态导入(取消服务器渲染,比如本地判断window、isMobile等)

    页面中的各种组件也可以动态导入(先显示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.导入google字体,创建_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
                href="https://fonts.googleapis.com/css2?family=Lobster"
                rel="stylesheet"
              />
              <link
                href="https://fonts.googleapis.com/css2?family=Roboto Condensed"
                rel="stylesheet"
              />
    
            </Head>
            <body>
              <Main />
              <NextScript />
            </body>
          </Html>
        );
      }
    }
    
    export default MyDocument;
    
    

    9.部署服务器nginx

    1. 部署到自己的服务器上(联系后台人员进行配置)

    http://www.shanhuxueyuan.com/news/detail/111.html
    nextjs打包后的文件存储在.next文件夹,但是只有这个文件夹下的内容是不够的,因为要在node端运行,还需要next以及react及reactDom等,简单起见,我们可以把整个项目都传到服务器。这样的缺点就是node_modules比较大,不过这样最简单。 在服务器端,进入项目路径 依次执行 npm run build ,npm run start即可将项目运行在服务器端,默认是localhost:3000,我们肯定是要通过域名访问项目,因此还需要进行域名配置,可通过nginx反向代理来实现。

    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;
      }
    }
    
    • 现在可以通过域名访问了,但是还是存在一个问题,就是我们刚才执行的npm run start命令,必须打开命令行才有效,一旦关闭命令行,进程也终止了,简单的做法就是通过nohup在后台执行 npm run start ,这样关闭命令行仍然有效。
    nohup   npm run start &
    
    • PM2是node进程管理工具,可以利用它来简化很多node应用管理的繁琐任务,如性能监控、自动重启、负载均衡等,而且使用非常简单
      npm install -g pm2
      为了简单的使用pm2,我们先把项目下的package.json中添加一个server指令,server指令依次执行next build和next start
    "scripts": {
      "dev": "next",
      "build": "next build",
      "start": "next start",
      "server":"next build && next start", //添加server指令
    },
    

    进入到项目所在目录
    执行如下命令

    pm2 start npm --name yourName -- run server --watch
    

    将yourName换成你的项目名,这个是给这个进程起的名称,可以随意
    --watch代表监听项目文件,当文件发生变化是,自动重新加载如下指令,这样就很方便了,当我们更改代码之后,只需要传到服务器即可,pm2会自动监听,重新执行 npm run server

    这样就完成服务器部署了,可能有的同学还想服务器重启之后自动运行这个命令,使用pm2也很简单只需执行如下命令即可

    pm2 startup
    

    2. 部署到vercel上(最后的链接如此:https://nextjs-demo-self.vercel.app/

      1. 将代码push到自己的github
    • 2.打开https://vercel.com/dashboard用自己的github账号登录,选择项目
      1. 如果自定义了输出目录这里也要改成一致
    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:'',
        }
    }
    
    image.png
      1. deploy

    相关文章

      网友评论

        本文标题:next.js 初步开发到部署

        本文链接:https://www.haomeiwen.com/subject/vahzgrtx.html