Generate framework code tool tool - Mitosis

foreword

In our daily work, when we write components, we may need to consider the following scenarios of version upgrades, technology migrations, or external component provision:

  • vue2 upgrade vue3
  • Vue3 migrates to react or react migrates to vue3
  • Usually, externally provided components should contain two versions of react and vue
  • Various frameworks are used in the system

Normally, we need to analyze and implement the two versions of react and vue. In order to ensure the UI and interaction consistency of the two, we need to maintain them separately, which naturally increases our workload...

So is there a tool that can help us achieve: write once, compile and output multiple framework codes at the same time?

What's the Mitosis?

Mitosis is a tool that writes components once and can be compiled into each framework. It is very simple and has its own set of syntax, similar to react. Let's look at components written in Mitosis and compile them into react, vue2, and vue3 components at the same time

  • Components written in Mitosis

image.png

  • Let's first convert to react, vue2, vue3, webcomponent type code

image.png

  • instantly flew up

Let's fly!

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

2. Configure package.json

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

4. Configure tsconfig.json

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

5. Implement PhoneNumberInput with mitosis

/**
 * 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. Execute npm run build

Generate code for configured targets

How to view the effect when writing components

Builder.io's JJS-lite fiddle to see the result visualized

Guess you like

Origin juejin.im/post/7226248402799312951