创建项目

使用前请确认 Node 版本 >= 10,推荐使用最新版 Node.js(12.x 或 14.x)

如果未安装过,请先安装 @midwayjs/faas-cli 工具。

  1. $ npm i @midwayjs/faas-cli -g

生成示例代码

使用命令生成示例代码。

  1. $ f create --template-package=@midwayjs-examples/midway-hooks-react

有点大,网慢可能需要等待一下。

  1. ➜ applications of create --template-package=@midwayjs-examples/faas-with-react
  2. Generating boilerplate...
  3. ✔ The directory where the service should be created · react_xxx
  4. 1...
  5. 2...
  6. 3...
  7. Enjoy it...
  8. Successfully generated boilerplate for template: "@midwayjs-examples/midway-hooks-react"
  9. Usage:
  10. - cd react_xxx
  11. - npm install
  12. - npm run test
  13. - and read README.md
  14. Document ❤ Star: https://github.com/midwayjs/midway

本地开发

整个示例代码结构如下。

  1. ➜ react_xxx tree
  2. .
  3. ├── README.md
  4. ├── config-overrides.js
  5. ├── f.yml # 函数配置文件
  6. ├── package.json
  7. ├── public
  8. │ ├── favicon.ico
  9. │ ├── index.html
  10. │ ├── logo192.png
  11. │ ├── logo512.png
  12. │ ├── manifest.json
  13. │ └── robots.txt
  14. ├── src
  15. │ ├── App.test.tsx
  16. │ ├── App.tsx
  17. │ ├── Home.tsx
  18. │ ├── List.tsx
  19. │ ├── apis # 函数目录
  20. │ │ ├── config
  21. │ │ │ └── config.default.ts
  22. │ │ ├── configuration.ts
  23. │ │ ├── hook
  24. │ │ │ └── useMethod.ts
  25. │ │ ├── lambda # 接口目录
  26. │ │ │ └── index.ts
  27. │ │ └── render.ts # 页面渲染函数
  28. │ ├── index.css
  29. │ ├── index.tsx
  30. │ ├── logo.svg
  31. │ ├── react-app-env.d.ts
  32. │ ├── serviceWorker.ts
  33. │ ├── setupProxy.js
  34. │ └── setupTests.ts
  35. └── tsconfig.json
  36. 6 directories, 27 files

我们在本地可以通过 npm start 来启动,启动时会自动发一个请求到函数端拿数据,渲染到页面,访问 [http://127.0.0.1:3000/](http://127.0.0.1:8080/) ,整体效果如下。

image.png

切换顶部的 Tab 区域,还会请求不同的函数接口。

部署

使用 f deploy ,默认发布到阿里云,也可以自行修改到其他平台。