Giter Site home page Giter Site logo

jsx-info's Introduction

jsx-info

Displays a report of JSX component and prop usage.

Watch my demonstration video for more information.

Why

First of all, I thought it would be cool to see all this info. But more importantly, I think jsx-info can be used to help refactor your code.

Let's say you have a component called <DataTable> that takes 43 different props. If you needed to rewrite <DataTable> from scratch, you might not want to keep as many different props. Using jsx-info you could analyze which props get used the most and start porting that functionality first.

If the usage of a particular prop is very low, you might even choose to get rid of that prop and rewrite the calling code to use something else instead.

The intended workflow here is to run jsx-info and compare the data with your prop-types or TypeScript type definitions to find discrepencies.

Installation

Automatically install and run jsx-info:

$ npx jsx-info

(Optional) Install locally to your project to speed up repeated usage:

$ npm i -D jsx-info
$ npx jsx-info

Usage

$ npx jsx-info

jsx-info hooks into .gitignore files to automatically ignore files that are not part of your project (typically node_modules/ and other directories). It does not have any other way of filtering out files, currently.

If you pass additional arguments, they are JSX element names to scan for (instead of scanning every JSX element):

$ npx jsx-info div button React.Fragment

By default jsx-info starts scanning in the current directory, but you can use a different directory like this:

$ npx jsx-info --directory app/src

Find <Button kind="primary">

$ npx jsx-info --report lines --prop kind=primary Button

Find all uses of the prop id

$ npx jsx-info --report lines --prop id

Configuration

In order to avoid repeating command line arguments as often, jsx-info supports reading command line argument defaults from a configuration file. You can either put defaults in a .jsx-info.json file or under a key named "jsx-info" in your package.json file.

Either way, your configuration should be JSON that looks like this, where every key is optional:

{
  "babelPlugins": ["decorators-legacy", "pipelineOperator"],
  "directory": "src",
  "ignore": ["**/__test__", "legacy/**"],
  "files": ["**/*.{js,jsx,tsx}"]
}

Documentation

You can use jsx-info as a JS library.

const { analyze } = require("jsx-info");

const analysis = await analyze({
  /* Options */
});

Options and data structures are documented in api.ts.

Note

jsx-info strives to parse all standard JS, JSX, and TypeScript syntax. This means that only stage-3 or higher proposals will be supported. I do not recommend using non-official JS syntax in your project.

If you are having problems with jsx-info parsing your code, please file an issue. There are many options I can pass to Babel's parse function, and I'm trying to be conservative with how many I pass.

Contributions

Please read the Code of Conduct before contributing to the project. It is non-negotiable.

All types of contributions are welcome: code, documentation, questions, suggestions, etc. Yes, I think questions are a form of contribution. The only way I can make this tool better is by getting feedback from users.

License

Copyright © Brian Mock under the MIT License.

jsx-info's People

Contributors

dependabot[bot] avatar jasonmit avatar hassanhe avatar

Stargazers

Igor Shmyrin avatar Alexandre Stahmer avatar umbertod avatar Katherine Martinez avatar James R. Zygmont avatar Lei Ma avatar Ahmad Nasr avatar Joel Hassan avatar Anders D. Johnson avatar Diego Giuliani avatar Yasin ATEŞ avatar  avatar Clay Stewart avatar Abhishek Bangar avatar  avatar Tommy D. Rossi avatar Matt Hamlin avatar Anthony Thompson avatar Abayomi Akintomide avatar Artem Sapegin avatar Toni avatar Philipp Schneider avatar nikhil avatar Tom Bonnike avatar Sayed Rafeeq avatar Andrey Okonetchnikov avatar Samuel Hobl avatar Jeremy avatar Travis Arnold avatar David Clark avatar Matthew Jarvis Wall avatar  avatar Joe Kane avatar  avatar Robert Khayat avatar Jay Fallon avatar Andrew McNamara avatar Jaon avatar Ray Yee avatar Sam Gluck avatar Vadim Demedes avatar Fannar Snær Harðarson avatar Divyagnan Kandala avatar Michael Alaev avatar Wei Zhu avatar krinoid avatar Michael Demarais avatar Patrick Lienau avatar Jack Hanford avatar Ryan Ashcraft avatar  avatar Vivek Jilla avatar  avatar Daniel Bank avatar Gabor Dolla avatar Jamie Mason avatar Matt Menzenski avatar Martin Beierling-Mutz avatar Vesa Vänskä avatar  avatar Thomas Scharke avatar Phellipe Andrade avatar Faiyaz Shaikh avatar Pritam Barhate avatar Rizvi Iqubal avatar Brad Westfall avatar Dan Train avatar Jidé avatar Antoine avatar Ayrton avatar Tahseen Malik avatar Ben Puckhaber avatar Damien Varron avatar Kostas Manionis avatar Kristóf Poduszló avatar Timon van Spronsen avatar Igor avatar Khodor Ammar avatar Ori Livni avatar Wouter De Schuyter avatar Yannick Croissant avatar monjer avatar Eugene Tropin avatar Julien Cavaleiro avatar Fotis Papadogeorgopoulos avatar Maina Nick avatar Oleg Lustenko avatar Arctic Ice Studio avatar Ivan Babak avatar Artur Parkhisenko avatar  avatar Cygra Wang avatar

Watchers

Sage Fennel avatar James Cloos avatar  avatar

jsx-info's Issues

Add option to return prop values

I'm using this package with jest to check that all used strings by react-intl are in file with localization.

So, I'm using this package to find all <FormattedMessage id="..." defaultMessage="..."> component usage, extract it by id and compare that this id is exist in all localized files.

Unfortunately, analyze() method doesn't include prop values and almost methods are private, so I'm using too dirty way to use your package with rewire package :)

// All methods are private, so rewire is needed to access into them
const jsxInfoApi = rewire('jsx-info/dist/src/api');

const parseJsxInfo = jsxInfoApi.__get__('parse');
const createPropJsxInfo = jsxInfoApi.__get__('createProp');

...

const filenames = await globby([
    'containers/**/*.jsx',
    'components/**/*.jsx',
    'mappings.jsx',
  ], {
    absolute: true,
    onlyFiles: true,
    gitignore: true,
    ignore: [],
    cwd: directory,
  });

  filenames.forEach((filename) => {
    try {
      const code = fs.readFileSync(path.resolve(directory, filename), 'utf8');

      parseJsxInfo(code, {
        babelPlugins: [],
        typescript: filename.endsWith('.tsx') || filename.endsWith('.ts'),
        onlyComponents: [
          'FormattedMessage',
          'CustomHeadingComponent',
          'FormRow',
          'DataRow',
          'InfoRow',
        ],
        onComponent: ({ node }) => {
          node.openingElement.attributes.forEach((propNode) => {
            const propValue = propNode.value.value;
            const propName = createPropJsxInfo(propNode);

            // ... here propName is validated and propValue is used
          });
        },
      });
    } catch (error) {
      throw error;
    }
  });

It covers 99% of my cases, except variables.

What do you think is better?

  1. Update analyze() method to include prop values as well? It might be good, but how to deal with non-string props?
  2. To export private methods?
  3. Keep as is :)

Thanks for this awesome package!

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.