首頁 > web前端 > js教程 > 主體

使用 Github 頁面部署 React Next.js 應用程式的步驟

Linda Hamilton
發布: 2024-10-12 06:30:02
原創
490 人瀏覽過

teps to deploy your React Next.js app with Github pages

Deploying a Next.js app to GitHub Pages can be a bit tricky due to the static nature of GitHub Pages and the dynamic features of Next.js. In this article, I'll walk you through the steps to successfully deploy do it.

Prerequisites

  • A GitHub account
  • Node.js and npm installed on your machine
  • A Next.js project ready to deploy

Step 1: Install gh-pages

npm install gh-pages --save-dev

Step 2: Update next.config.mjs

Next, you need to update your next.config.js (or next.config.mjs) file to handle the base path and asset prefix correctly.

const isProd = process.env.NODE_ENV === 'production';
const nextConfig = {
  reactStrictMode: true,
  images: {
    unoptimized: true, // Disable default image optimization
  },
  assetPrefix: isProd ? '/your-repository-name/' : '',
  basePath: isProd ? '/your-repository-name' : '',
  output: 'export'
};

export default nextConfig;
登入後複製

isProd checks if the NODE_ENV environment variable is set to 'production'. If it is, isProd will be true; otherwise, it will be false.
Conditional assetPrefix and basePath are set to your repository name only if isProd is true. Otherwise, they are set to an empty string for local development.
The images.unoptimized option is set to true to disable the default image optimization, which is not compatible with static exports.

Step 3: Update package.json

Update your package.json to include the homepage field and the deploy scripts.

"homepage": "https://<your-github-username>.github.io/<your-repo-name>",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d out"
  },
登入後複製

Replace and with your GitHub username and repository name.

Step 4: Deploy Your App

Run npm run predeploy and npm run deploy

These commands will:

  • Build your project.
  • Export it to the out directory.
  • Deploy it to the gh-pages branch on GitHub. Push your work to your GitHub branch before the next step

Step 5: Configure GitHub Pages

Go to your repository on GitHub.
Navigate to Settings > Pages.
Under Source, select the gh-pages branch.
Save the settings.
Add manually the .nojekyll file at the root of the gh-pages branch on GitHub. Learn more about this here.

Step 6: Verify Deployment

After deploying, open your GitHub Pages URL (e.g., https://.github.io/) to verify that your app is live.

And voila!

Feel free to leave any questions or comments below. Happy coding!

以上是使用 Github 頁面部署 React Next.js 應用程式的步驟的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!