生成框架代码工具利器-Mitosis

前言

日常工作中,我们在编写组件时,可能需要考虑后面的版本升级、技术迁移或者对外提供组件的场景:

  • vue2 升级 vue3
  • vue3 迁移至 react 或者 react 迁移至 vue3
  • 通常情况下,对外提供组件要包含 react 和 vue 两个版本
  • 系统中使用多种框架

通常情况下,那么我们需要分析实现 react 和 vue 这两个版本,为了保证两者UI、交互一致性,我们需要分别进行维护,自然而然增加了我们的工作量...

那么有没有一种工具能帮我们实现:一次编写,同时编译输出多种框架代码么?

What's the Mitosis?

Mitosis 是一种一次编写组件,可以编译到每种框架中的工具,它非常简单,有自己的一套语法,类似 react,下面我们看用Mitosis编写的组件,同时编译成react、vue2、vue3组件

  • 用 Mitosis 编写的组件

image.png

  • 我们先转成 react、vue2、vue3、webcomponent类型代码

image.png

  • 瞬间飞起来了

Let's fly!

  1. 安装
npm install --save-dev @builder.io/mitosis-cli @builder.io/mitosis watch
复制代码

2.配置package.json

  "scripts": {
    "build": "npm run mitosis",
    "start": "watch 'npm run mitosis ./src ./overrides'"
  },
复制代码
  1. 配置 完整配置
module.exports = {
   // 入口文件
   files: 'src/**',
   // 编译目标
   targets: ['vue2', 'vue3', 'react', 'webcomponent'],
   // 默认 output
   dest: 'overrides',
   exclude: []
};
复制代码

4.配置tsconfig.json

    "strict": true,
    "target": "es5",
    "jsx": "preserve",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "jsxImportSource": "@builder.io/mitosis"
复制代码

5.用mitosis实现 PhoneNumberInput

/**
 * PhoneNumberInput component.
 */
import { useState } from '@builder.io/mitosis';

export default function PhoneNumberInput(props: any) {
	const [phone, setPhone] = useState('');

	function formatPhone(value: string): string {
		let val = value.replace(/\D/g, '');
		if (val.length > 10) {
			val = val.slice(0, 10);
		}
		if (val.length > 6) {
			val = `${val.slice(0, 6)}-${val.slice(6)}`;
		}
		if (val.length > 3) {
			val = `(${val.slice(0, 3)})${val.slice(3)}`;
		}

		return val;
	}

	return (
		<input
			type='tel'
			class='phone-number-input'
			data-testid='phone-number-input'
			placeholder='please input'
			value={phone}
			onChange={e => setPhone(formatPhone(e.target.value))}
		/>
	);
}
复制代码

6.执行 npm run build

生成已配置的targets的代码

编写组件时,如何查看效果

Builder.io的JJS-lite fiddle看到可视化的结果

猜你喜欢

转载自juejin.im/post/7226248402799312951