使用Cloudflare Workers部署Nuxt3

2/15/2023 javascriptNuxt3

# 相关文档

https://nitro.unjs.io/deploy/providers/cloudflare (opens new window)

# 部署流程

  • 授权登录wrangler

    npx wrangler login
    
    1
  • 获取account_id

    npx wrangler whoami
    
    1
  • nuxt3项目根目录创建wrangler.toml文件

      name = "yourprogramname"
      main = "./.output/server/index.mjs"
      workers_dev = true
      compatibility_date = "2022-09-10"
      account_id = "<account_id>"
      route = "<设置自定义域名 (可选项)>"
      [site]
      bucket = ".output/public"
    
    1
    2
    3
    4
    5
    6
    7
    8
  • 打包项目

    NITRO_PRESET=cloudflare pnpm build
    
    1
  • 部署到Cloudflare

    npx wrangler publish
    
    1

    至此已成功手动部署项目到workers

# 使用Github Actions自动部署

  • Github该项目的settings -> Secrets and variables -> Actions 创建一个CF_API_TOKENToken获取流程看这里 (opens new window)

  • 创建文件.github/workflows/cloudflare.yml

    name: cloudflare
    
    on:
      push:
    	branches: [ master ]
      pull_request:
    	branches: [ master ]
    
      workflow_dispatch:
    
    jobs:
      ci:
    	runs-on: ${{ matrix.os }}
    
    	strategy:
    	  matrix:
    		os: [ ubuntu-latest ]
    		node: [ 16 ]
    
    	steps:
    	  - uses: actions/setup-node@v1
    		with:
    		  node-version: ${{ matrix.node }}
    
    	  - name: Checkout
    		uses: actions/checkout@master
    
    	  - name: Setup PNPM
    		uses: pnpm/action-setup@v2.2.4
    		with:
    		  version: 7.13.2
    
    	  - name: Cache node_modules
    		uses: actions/cache@v2
    		with:
    		  path: node_modules
    		  key: ${{ matrix.os }}-node-v${{ matrix.node }}-deps-${{ hashFiles(format('{0}{1}', github.workspace, '/pnpm-lock.yaml')) }}
    
    	  - name: Install Dependencies
    		if: steps.cache.outputs.cache-hit != 'true'
    		run: pnpm i
    
    	  - name: Build
    		run: pnpm build
    		env:
    		  NITRO_PRESET: cloudflare
    
    	  - name: Publish to Cloudflare
    		uses: cloudflare/wrangler-action@2.0.0
    		with:
    		  apiToken: ${{ secrets.CF_API_TOKEN }}
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
  • 搞定!

Last Updated: 9/22/2023, 6:04:11 AM