Skip to content

Conversation

@Nauja
Copy link
Contributor

@Nauja Nauja commented Jul 7, 2021

Proposed changes

I wrote a new plugin for purgecss to extract id, class and tag attributes from TSX files.

Types of changes

  • Bugfix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)

Checklist

  • Lint and unit tests pass locally with my changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Further comments

It's me again, I wrote another plugin for purgecss on top of purgecss-from-jsx to extract id, class and tag attributes from TSX files.

You will find a working test in purgecss-from-tsx/__tests__.

Basically this plugin compiles a TSX string to JSX using typescript and jsx: ts.JsxEmit.Preserve, then call purgecss-from-jsx to extract attributes:

import acorn from "acorn";
import * as ts from "typescript";
import purgeFromJsx from "purgecss-from-jsx";

function purgeFromTsx(options?: {
  acornOptions?: acorn.Options,
  tsOptions?: ts.CompilerOptions
}): (content: string) => string[] {
  return (content: string): string[] => {
    return purgeFromJsx(options?.acornOptions)(
      ts.transpileModule(content, {
        compilerOptions: {
          jsx: ts.JsxEmit.Preserve,
          ...options?.tsOptions
        }
      }).outputText
    );
  };
}

It is needed because purgecss-from-jsx can't parse a .tsx file like:

import PropTypes from "prop-types";
import React from "react";

type MyComponentProps = {
  login: any;
};

type MyComponentState = {
  username: string;
  password: string;
};

class MyComponent extends React.Component<MyComponentProps, MyComponentState> {
  static propTypes: any;

  render() {
    return (
      <React.Fragment>
        <div className="test-container">Well</div>
        <div className="test-footer" id="an-id"></div>
        <a href="#" id="a-link" className="a-link"></a>
        <input id="blo" type="text" disabled/>
      </React.Fragment>
    );
  }
}

MyComponent.propTypes = {
    login: PropTypes.func.isRequired
};

export default MyComponent;

I made a small change to prugecss-from-jsx because options can be optionnal:

- function purgeFromJsx(options: acorn.Options) {
+ function purgeFromJsx(options?: acorn.Options) {

@Ffloriel Ffloriel merged commit e556afc into FullHuman:master Jul 25, 2021
@Ffloriel
Copy link
Member

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants