jsx-instruction
TypeScript icon, indicating that this package has built-in type declarations

0.3.2 • Public • Published

JSX Instruction

| EN: English | ZH: 中文

Based on the support for TypeScript namespaced-jsx-attributes, this repository implements a custom directive system for components.

In JSX, you can use the postfix directive onClick:stop={noop} to prevent event bubbling using the stop directive.

You can also use the syntax foo:boolean='y' to set the boolean type data for foo using the boolean directive.

How to Use

Installation

npm install jsx-instruction
# or
yarn add jsx-instruction
# or
pnpm add jsx-instruction

Configuration

Currently, only React is supported, so we'll use React as an example:

  • tsconfig.json: Configure jsxImportSource to jsx-instruction/react
{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "jsx-instruction/react"
  }
}
  • App.ts:Import types and default instruction
import 'jsx-instruction/common'

import type { } from 'jsx-instruction/react'

Use

export function Foo() {
  return <div onClick={noop}>
    <button onClick={noop}>
      click will bubble
    </button>
    <button onClick:stop={noop}>
      click will not bubble
    </button>
  </div>
}

Custom Directives

When it comes to directives, there are no specific restrictions on where they should be placed. They can be placed before or after an attribute. Commonly used directives may include:

  • attr:stop
  • model:attr

Directives function similarly to decorators in the ECMAScript standard. They can modify a property that needs to be passed into a component. (Alternatively, they can modify the return object of the current component, although this design and implementation have not been done yet, similar to Vue's v-loading directive.)

common

  • stop.plugin.ts
import { defineInstruction, Instruction } from 'jsx-instruction'

declare module 'jsx-instruction' {
  interface InstructionMap {
    stop: Instruction<
      (e: { stopPropagation(): void }) => void | Promise<void>
    >
  }
}

defineInstruction('stop', [func => e => {
  if (e.stopPropagation && typeof e.stopPropagation === 'function') {
    e.stopPropagation()
  }
  return func(e)
}])

Readme

Keywords

none

Package Sidebar

Install

npm i jsx-instruction

Weekly Downloads

2

Version

0.3.2

License

MIT

Unpacked Size

21 kB

Total Files

21

Last publish

Collaborators

  • yijie4188