Published 2022-08-21

Chrome插件开发 - 使用React开发扩展

在上一篇文章【Add Tailwind】学习了集成 tailwind。

这篇文章学习使用 react 创建一个新标签插件,类似如图:

也可以使用其他自己喜欢的框架:vue、angular、svlete 等

安装 React

npm install react react-dom
touch -p index.js src/{App,Counter}.js
vim new-tab.html

new-tab.html

<body>
  <div id="app"></div>
  <script type="module" src="index.js"></script>
</body>

index.js

import ReactDOM from 'react-dom'
import {App} from './src/App'

const app = document.getElementById('app')
ReactDOM.render(<App />, app)

App.js

import Counter from './Counter'
export function App() {
  return (
    <div className="flex flex-col items-center justify-center w-screen h-screen bg-indigo-400 text-6xl font-bold text-white">
      <p>Welcome 👋</p>
      <Counter />
    </div>
  )
}

Counter.js

import {useState} from 'react'

export default function Counter() {
  const [counter, setCounter] = useState(0)
  const increase = () => setCounter((count) => count + 1)
  const decrease = () => setCounter((count) => count - 1)
  return (
    <div>
      <button onClick={decrease}>-</button>
      <span className="px-4">{counter}</span>
      <button onClick={increase}>+</button>
    </div>
  )
}

跑起来

npm run build

测试插件

FMA6T1

可以在这里找到【Source Code】