vitejs / vite-plugin-react-swc

Speed up your Vite dev server with SWC
MIT License
830 stars 54 forks source link

Refresh does not always work with class components #199

Closed n9 closed 4 months ago

n9 commented 5 months ago

When it works

If a class component is exported from a module that also exports a functional component.

Sample:

import React from "react";

export class Bar1 extends React.Component {
    render() {
        return <span>Barx</span>
    }
}

export function DummyBarFc() {
    return <span>dummy</span>
}

When it does not work

If a class component is exported from a module that exports no functional component.

Sample:

import React from "react";

export class Bar1 extends React.Component {
    render() {
        return <span>Barx</span>
    }
}

// export function DummyBarFc() {
//     return <span>dummy</span>
// }

Why it does not work

The refresh runtime is only included https://github.com/vitejs/vite-plugin-react-swc/blob/21eef9eefd7ff3d46dc0a3132dac83d9bb49f980/src/index.ts#L161-L168

if the code of module matches https://github.com/vitejs/vite-plugin-react-swc/blob/21eef9eefd7ff3d46dc0a3132dac83d9bb49f980/src/index.ts#L29

However, the pattern is not generated by SWC for class components, as fast refresh does not preserve their state (see https://github.com/swc-project/swc/issues/4431#issuecomment-1108465296). So a module with no exported functional component is not handled by HMR.

(Note: I will provide a PR.)