[英]Sharing code between a Typescript React project and a Typescript Express project
I have been trying to come up with an elegant solution to share code between two projects that are closely related to each other.我一直在努力想出一个优雅的解决方案来在两个彼此密切相关的项目之间共享代码。
I have a React web app which simply includes all of the client code and I have an Express app which serves the React web app, but it also acts as an API. Because I use Typescript for both projects, I want to reuse some types.我有一个 React web 应用程序,它只包含所有客户端代码,我有一个 Express 应用程序,它为 React web 应用程序提供服务,但它也充当 API。因为我在两个项目中都使用 Typescript,所以我想重用一些类型。 To accomplish that, I created a
shared
project.为此,我创建了一个
shared
项目。
My current folder structures is as follows:我目前的文件夹结构如下:
Now I want to link the web-app
and server
projects with my shared
project, but there are some restrictions:现在我想将
web-app
和server
项目与我的shared
项目链接起来,但有一些限制:
npm link
I believe).npm link
)。 I am not sure whether my current structure of projects allows the functionality I need, so feel free to also suggest other folder structures.我不确定我当前的项目结构是否允许我需要的功能,所以请随意建议其他文件夹结构。
If you are using create-react-app
to create the web-app then you can easily use NODE_PATH
environment variable to do absolute imports without creating node modules. 如果要使用
create-react-app
创建Web应用程序,则可以轻松使用NODE_PATH
环境变量来进行绝对导入,而无需创建节点模块。
.env
file at the root level (same level as package.json
of web-app
directory) web-app
目录的package.json
相同的级别)创建一个.env
文件package.json
NODE_PATH
to shared/
( NODE_PATH=shared/
) NODE_PATH
为shared/
( NODE_PATH=shared/
) Now instead of doing something like 现在,而不是做类似的事情
import { editUser } from '../../../shared/actions';
you can use 您可以使用
import { editUser } from 'shared/actions';
Install eslint-plugin-import
to prevent eslint from throwing import errors. 安装
eslint-plugin-import
以防止eslint引发导入错误。 And update your .eslintrc
file as 并将您的
.eslintrc
文件更新为
{
"settings": {
"import/resolver": {
"node": {
"moduleDirectory": ["node_modules", "shared/"]
}
}
}
}
Add the following content to your .flowconfig
file 将以下内容添加到您的
.flowconfig
文件中
[options]
module.system.node.resolve_dirname=node_modules
module.system.node.resolve_dirname=shared
You can use yarn workspaces for that kind of purpose, There's a minimal working boilerplate I have created exactly for that kind of configuration: https://github.com/rok-tel/ts-express-react您可以将 yarn workspaces 用于这种目的,我为这种配置创建了一个最小的工作样板: https://github.com/rok-tel/ts-express-react
take a look at ./packages/shared
folder which is consumed both by server (express) and client (react)看一下
./packages/shared
文件夹,它被服务器(express)和客户端(react)消耗
Consider use Nx - https://nx.dev/考虑使用 Nx - https://nx.dev/
This is an awesome framework to manage monorepos.这是一个很棒的管理 monorepos 的框架。
Docs for creating the shared code package:用于创建共享代码 package 的文档:
https://nx.dev/l/r/tutorial/07-share-code https://nx.dev/l/r/tutorial/07-share-code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.