当基础要素设计在上期完成后,现在开始搭建工具的前端工程, 因为是做工具类 UI 组件,所以需要使用 Typescript 方便编译 ES5 且可维护类型的特性,为后续提供良好的维护性
npx create-react-app tools-webkit-memory --typescript
复制代码
或者使用全局的 create-react-app
create-react-app tools-webkit-memory
yarn add typescript @types/node @types/react @types/react-dom @types/jest
复制代码
然后是搭建 git 仓库来长期维护。如果是公司内部的组件,可能需要搭建一个私有制品库(后续会介绍)
用 create-react-app 创建完仓库后,在本地前端工程执行设置下面的命令来对齐:
git remote add origin git@gitee.com:windbringer/tools-webkit-memory.gitgit push -u origin master
复制代码
为了配套 typescript,还需要增加 tsconfig.json 文件
{ "compilerOptions": { "target": "es5", "module": "commonjs", "lib": ["DOM", "ES2015"], "allowJs": true, "declaration": true, "outDir": "./lib", "rootDir": "./src", "strict": true, "esModuleInterop": true }, "include": [ "src/**/*", ],}
复制代码
这里可以看到编译目标为 es5,主要是为了提高兼容性,避免各种低版本浏览器无法使用工具,虽然这次的内存工具是 webkit 专用,但为后续工具系列做模版,会参照此篇的搭建方式。
使用 typescript 编译,还需要在 package.json 增加构建命令
然后在命令行中运行刚刚添加的构建命令,可以看到如下
tim@Tim tools-webkit-memory % npm run build:ts
> tools-webkit-memory@0.1.0 build:ts /Users/tim/Documents/platform/tools-webkit-memory> tsc
tim@Tim tools-webkit-memory %
复制代码
这时,可以看到 lib 目录里生成的构建物是 es5 代码
"use strict";var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod };};Object.defineProperty(exports, "__esModule", { value: true });var logo_svg_1 = __importDefault(require("./logo.svg"));require("./App.css");function App() { return (<div className="App"> <header className="App-header"> <img src={logo_svg_1.default} className="App-logo" alt="logo"/> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer"> Learn React </a> </header> </div>);}exports.default = App;
复制代码
到这步以后,工具库项目的基础就快打好了。为了加快调试速度,减少发布版本来调试,可以在构建后使用 yarn link 命令来在本地环境关联这个库
tim@Tim tools-webkit-memory % yarn linkyarn link v1.22.4success Registered "tools-webkit-memory".info You can now run `yarn link "tools-webkit-memory"` in the projects where you want to use this package and it will be used instead.✨ Done in 0.12s.tim@Tim tools-webkit-memory %
复制代码
这里是将工具库链接到 yarn 中成为软链接,如果遇到重新构建代码没有正确刷新,还需要使用:
然后再重新 yarn link 才能达到刷新效果。
此时,在本地使用这个工具项目中可以在 package.json 的增加配置
"dependencies": { ... "tools-webkit-memory":"^0.1.0", ...}
复制代码
然后在使用这个工具的这个项目的目录下使用
yarn link "tools-webkit-memory"
复制代码
即可实现不用每次更改都升级版本才能实验的效果,以提高开发效率和库质量
评论