Giter Club home page Giter Club logo

babel-plugin-react-directives's Introduction

babel-plugin-react-directives

A babel plugin that provides some directives for react(any JSX), similar to directives of vue. And you can now try it online at playground.

Travis (.org) branch Codecov node npm GitHub

中文文档

Table of Contents

Usage

Requires node v10.0.0 or higher, babel v7.0.0 or higher.

Installation

use npm:

npm install --save-dev babel-plugin-react-directives
npm install --save react-directives-runtime

use yarn:

yarn add --dev babel-plugin-react-directives
yarn add react-directives-runtime

Configuring via .babelrc

{
  "plugins": [
    "react-directives"
  ]
}

Plugin options

{
  "plugins": [
    [
      "react-directives",
      {
        "prefix": "x"
      }
    ]
  ]
}
  • prefix: JSX props prefix for directives. Default: "x", example usage: x-if

Directives

x-if

If the x-if value is truthy, this element will be rendered, otherwise do not.

Example:

const foo = <div x-if={true}>text</div>

Convert to:

const foo = true ? <div>text</div> : null

x-else-if and x-else

The x-else-if must have a corresponding x-if. if x-if value is falsy, and x-else-if value is truthy, it will be rendered.

The x-else must have the corresponding x-if or x-if-else. When all corresponding x-if or x-else-if value are falsy, it will be rendered.

Example:

const foo = (
  <div>
    <p x-if={data === 'a'}>A</p>
    <p x-else-if={data === 'b'}>B</p>
    <p x-else-if={data === 'c'}>C</p>
    <p x-else>D</p>
  </div>
)

Convert to:

const foo = (
  <div>
    {data === 'a'
      ? <p>A</p>
      : data === 'b'
        ? <p>B</p>
        : data === 'c'
          ? <p>C</p>
          : <p>D</p>
    }
  </div>
)

x-show

The x-show controls the display or hiding of elements through the display of the style prop. If the x-show value is falsy, will set style.display = "none", otherwise do nothing.

Example:

const foo = <div x-show={true}>text</div>

Convert to:

const foo = (
  <div style={{
    display: true ? undefined : "none"
  }}>text
  </div>
)

Of course, it will also merge other style props by calling the mergeProps method, for example:

const foo = (
  <div
    style={{ color: 'red' }}
    x-show={true}
    {...extraProps}>
    text
  </div>
)

will be converted to:

const foo = (
  <div
    {...extraProps}
    style={{
      ...mergeProps.call(this, "style", [
        { style: { color: 'red' } },
        extraProps
      ]),
      display: true ? undefined : "none"
    }}>text
  </div>
)

x-for

The x-for is used to traverse arrays to generate elements.

The value should like: (item, index) in list

  • list: array for traversal
  • item: current value
  • index: current index (optional)

Note: If you use ESLint, you may receive an error that item and index are undeclared variables. Please install eslint-plugin-react-directives plugin to solve it.

Example:

const foo = (
  <ul>
    <li
      x-for={item in list}
      key={item.id}>{item.name}
    </li>
  </ul>
)

Convert to:

const foo = (
  <ul>
    {list.map(item => (
      <li key={item.id}>{item.name}</li>
    ))}
  </ul>
)

Also note that if used with x-if, the x-for has a higher priority, for example:

const foo = (
  <ul>
    <li
      x-for={item in list}
      x-if={item.name === 'alice'}
      key={item.id}>{item.name}
    </li>
  </ul>
)

will be converted to:

const foo = (
  <ul>
    {list.map(item => (
      item.name === 'alice'
        ? <li key={item.id}>{item.name}</li>
        : null
    ))}
  </ul>
)

x-class

The x-class for conditionally joining classNames together by classnames, and it is useful for dynamically generating className. Usage is the same as classnames, the binding value will be passed as a parameter to the classNames method.

Example:

const foo = <div x-class={{ abc: true, def: false }}>

Convert to:

const foo = <div className={classNames({ abc: true, def: false })}>
// className="abc"

Note: classNames method references runtime/classnames.js.

Of course, it will also merge other className props, for example:

const foo = <div x-class={{ abc: true, def: false }} className="xyz">

will be converted to:

const foo = <div className={classNames(["xyz", { abc: true, def: false }])}>
// className="xyz abc"

The x-class can also be used with css-modules, the usage is as follows:

import styles from './style.css';

const foo = (
  <div
    className={styles.foo}
    x-class={{
      [styles.bar]: true,
      [styles.qux]: false
    }}
  />
)

Related Packages

Known Issues

  • When using x-for in Typescript, the binding value item will report an error. The temporary solution is to declare the item variable before use. Such as declare let item: any. And it is not recommended to use x-for in Typescript.

CHANGELOG

See more information at: CHANGELOG

LICENSE

MIT

babel-plugin-react-directives's People

Contributors

dependabot[bot] avatar peakchen90 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

babel-plugin-react-directives's Issues

TypeScript does not understand x-if

Describe the bug
TypeScript does not understand x-if. Inside an x-if block, the passed variable should be evaluated for truthyiness, but it is not.

To Reproduce
Steps to reproduce the behavior:

The following code should do it:

type MyNameProps = {
    children: string
}

const MyName = ({ children }: MyNameProps) => (
    <div>{children}</div>
)

type MyComponentProps = {
    name: string | null
}

const MyComponent = ({ name }: MyComponentProps) => (
    <MyName x-if={name}>{name}</MyName>
)
// ...

Expected behavior
TypeScript compiles successfully and does not show any errors. {name} gets passed as a string to <MyName>.

Actual behavior
TypeScript complains that <MyName> requires children to be of type string, but string | null was passed.

Environment

  • OS: Ubuntu 20.04
  • node version: 16.14.2
  • babel version: 7.9.0
  • version: 2.0.1
  • TypeScript version: 4.6.3

not working with es6

hi I am really like this project because is very difficult to write code without directive
I really I don't know why is not working ,
just if you can init a project with configuration of your project ??

强烈建议增加对 jsx-runtime 的外部支持

最近开发组件库打包时发现,开发时jsx转换是用babel插件转换的,功能开发没有问题。
但是由于现在react17开始,react的jsx语法打包时是通过react/jsx-runtime来转换新的JSX转换方式——React 官方博客翻译,导致打包后的代码,并没有转换x-指令,通过翻阅资料和查看源码,本插件过渡依赖@babel/plugin-transform-react-jsx,可以多增加一个包来处理这样的场景。

可参考:通过 jsx-runtime 实现自动使用 classnames / clsx

x-for doesn't work with TypeScript

As I understand, a TypeScript transformer is needed to solve this problem. Are you planning to create it in the future?

image

Application created with create-react-app --typescript

Config extended with react-app-rewired

const {
    override,
    disableEsLint,
    useBabelRc
  } = require('customize-cra')
  
  module.exports = override(
    disableEsLint(),
    useBabelRc()
  )

.babelrc

{
    "plugins": [
      "react-directives",
      "@babel/transform-react-jsx"
    ]
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.