nx 全栈应用脚手架探求

前言

为什么要倒置这个呢,首先是这种全栈架构的脚手架其实挺少的,而开始作为一个入门小白,这种能帮你折腾好前后端环境的玩意还是很新奇的,所以在学习Flask+Vue的过程中我就开始在Github上找相关的东西,奈何这样的组合实在偏冷门,所以一无所获

万幸的是在学Nest时还真让我找到了个不错的2K+星的全站脚手架,Nx。

简介

1
简单说说这个脚手架,自从nest.js越来越火之后,nest.js模仿的本体,也就是Angular一定程度上又吸引了一波关注,现在就等着一个以React为蓝本的Node.js框架出现了。。

由于风格相同,nx果断把基于nest.js和Angular的全栈脚手架搬上舞台,配合其别具一格的工作空间的理念,安装上手还都挺方便。

正是基于此,Nx又放眼React,并推出React+Express的全栈架构,这也是本文探索的起点。

安装

yarn create nx-workspace

随后,我们可以看到nx的选项卡:

? Workspace name (e.g., org name)     nxfullstack
? What to create in the new workspace react-express     [a workspace with a full stack application (React + Express)]
? Application name                    nxfullstack
? Default stylesheet format           emotion           [ https://emotion.sh]

这个我创建一个React+Express时用的选项,由于React的原因,CSS方面我选择了强烈推荐的emotion,这个是后话。

当然如果你想组合React+Nest.js的方式当然也是可行的,虽然直接选项并没有这个:

> empty             [an empty workspace]
  web components    [a workspace with a single app built using web components]
  angular           [a workspace with a single Angular application]
  angular-nest      [a workspace with a full stack application (Angular + Nest)]
  react             [a workspace with a single React application]
  react-express     [a workspace with a full stack application (React + Express)]
  next.js           [a workspace with a single Next.js application]

你可以选择空项目,然后自己添加前端库,再用后端绑定添加到前端的方式。这些在Nx中都有相对指令。

同时Nx也集成了e2e测试,这里也涉及了一个小bug.

一个小BUG

不知道是不是因为网络原因,由于我使用的是tyarn进行安装,在进行到测试框架相关的步骤,安装会在:

document-register-element...
cypress...

卡住。。。

后来我使用,npm发现也是这个问题,这么看来好像不是tyarn 的错。

这个问题直到我把AppData/temp/cypress文件删除之后,才顺利完成,不清楚是不是因为这个文件夹的缘故还是nx本身的问题。

简单的使用

对于创建好的项目,package.json中并没有关于后端库运行之类的脚本,需要自己根据workspace.json中的i相关内容进行添加,开发阶段,我们只需要这样即可:

    "start": "nx serve",
    "api": "nx serve api",

对应workspace.json中的api部分:
在这里插入图片描述
除此之外,还包括e2e的相关内容以及ts编写的API 接口类型。

最后贴上 demo的tsx文件,运用到了简单的 emotion和fetch获取后端数据的部分以及对于ts接口类型的调用:

import React, { useEffect, useState } from 'react';
import { Message } from '@nxfullstack/api-interfaces';
import styled from '@emotion/styled';

export const App = () => {
  const [m, setMessage] = useState<Message>({ message: '' });

  useEffect(() => {
    fetch('/api')
      .then(r => r.json())
      .then(setMessage);
  }, []);

  const Button = styled.button`
    color: turquoise;
    background-color: pink;
  `;

  return (
    <>
      <div style={{ textAlign: 'center' }}>
        <h1>Welcome to nxfullstack!</h1>
        <img
          width="450"
          src="https://raw.githubusercontent.com/nrwl/nx/master/nx-logo.png"
        />
        <Button>123</Button>
      </div>
      <div>{m.message}</div>
    </>
  );
};

export default App;

发布了346 篇原创文章 · 获赞 330 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43870742/article/details/103651377