Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React: Fix fast refresh #12535

Merged
merged 3 commits into from
Sep 21, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 71 additions & 29 deletions app/react/src/server/framework-preset-react.test.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,96 @@
import webpack from 'webpack';
import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin';
import * as preset from './framework-preset-react';
import type { StorybookOptions } from './types';

const mockApply = jest.fn();
jest.mock('@pmmmwh/react-refresh-webpack-plugin', () => {
return jest.fn().mockImplementation(() => {
return { apply: mockApply };
});
});

describe('framework-preset-react', () => {
const babelLoaderPath = require.resolve('babel-loader');
const reactRefreshPath = require.resolve('react-refresh/babel');
const webpackConfigMock: webpack.Configuration = {
mode: 'development',
plugins: [],
module: {
rules: [],
},
};
const babelConfigMock = {};

describe('webpackFinal', () => {
it('should return a config with fast refresh plugin when fast refresh is enabled', () => {
const config = preset.webpackFinal(webpackConfigMock, {
reactOptions: { fastRefresh: true },
} as StorybookOptions);
const storybookOptions: Partial<StorybookOptions> = {
configType: 'DEVELOPMENT',
presets: {
apply: async () => ({
fastRefresh: true,
}),
},
presetsList: [],
};

const storybookOptionsDisabledRefresh: Partial<StorybookOptions> = {
configType: 'DEVELOPMENT',
presets: {
apply: async () => ({
fastRefresh: false,
}),
},
};

describe('babel', () => {
it('should return a config with fast refresh plugin when fast refresh is enabled', async () => {
const config = await preset.babel(babelConfigMock, storybookOptions as StorybookOptions);

expect(config.module.rules).toEqual([
{
test: /\.[jt]sx?$/,
exclude: /node_modules/,
use: [
{
loader: babelLoaderPath,
options: {
plugins: [reactRefreshPath],
},
},
],
},
]);
expect(config.plugins).toEqual([reactRefreshPath]);
});

it('should not return a config with fast refresh plugin when fast refresh is disabled', () => {
const config = preset.webpackFinal(webpackConfigMock, {
reactOptions: { fastRefresh: false },
it('should return unchanged config without fast refresh plugin when fast refresh is disabled', async () => {
const config = await preset.babel(
babelConfigMock,
storybookOptionsDisabledRefresh as StorybookOptions
);

expect(config).toEqual(babelConfigMock);
});

it('should return unchanged config without fast refresh plugin when mode is not development', async () => {
const config = await preset.babel(babelConfigMock, {
...storybookOptions,
configType: 'PRODUCTION',
} as StorybookOptions);

expect(config.module.rules).toEqual([]);
expect(config).toEqual(babelConfigMock);
});
});

describe('webpackFinal', () => {
it('should return a config with fast refresh plugin when fast refresh is enabled', async () => {
const config = await preset.webpackFinal(
webpackConfigMock,
storybookOptions as StorybookOptions
);

expect(config.plugins).toEqual([new ReactRefreshWebpackPlugin()]);
});

it('should return unchanged config without fast refresh plugin when fast refresh is disabled', async () => {
const config = await preset.webpackFinal(
webpackConfigMock,
storybookOptionsDisabledRefresh as StorybookOptions
);

expect(config).toEqual(webpackConfigMock);
});

it('should not return a config with fast refresh plugin when mode is not development', () => {
const config = preset.webpackFinal({ ...webpackConfigMock, mode: 'production' }, {
reactOptions: { fastRefresh: true },
it('should return unchanged config without fast refresh plugin when mode is not development', async () => {
const config = await preset.webpackFinal(webpackConfigMock, {
...storybookOptions,
configType: 'PRODUCTION',
} as StorybookOptions);

expect(config.module.rules).toEqual([]);
expect(config).toEqual(webpackConfigMock);
});
});
});
57 changes: 29 additions & 28 deletions app/react/src/server/framework-preset-react.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,27 @@
import { TransformOptions } from '@babel/core';
import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin';
import type { Configuration } from 'webpack';

import { logger } from '@storybook/node-logger';
import type { StorybookOptions } from './types';
import type { StorybookOptions } from '@storybook/core/types';

export async function babel(config: TransformOptions, options: StorybookOptions) {
const isDevelopment = options.configType === 'DEVELOPMENT';
const reactOptions = await options.presets.apply('reactOptions', {}, options);
const fastRefreshEnabled =
isDevelopment && (reactOptions.fastRefresh || process.env.FAST_REFRESH === 'true');

if (!fastRefreshEnabled) {
return config;
}

return {
...config,
plugins: [require.resolve('react-refresh/babel'), ...(config.plugins || [])],
};
}

export function babelDefault(config: TransformOptions) {
export async function babelDefault(config: TransformOptions) {
return {
...config,
presets: [
Expand All @@ -16,35 +33,19 @@ export function babelDefault(config: TransformOptions) {
};
}

export function webpackFinal(config: Configuration, { reactOptions }: StorybookOptions) {
const isDevelopment = config.mode === 'development';
export async function webpackFinal(config: Configuration, options: StorybookOptions) {
const isDevelopment = options.configType === 'DEVELOPMENT';
const reactOptions = await options.presets.apply('reactOptions', {}, options);
const fastRefreshEnabled =
isDevelopment && (reactOptions?.fastRefresh || process.env.FAST_REFRESH === 'true');
if (fastRefreshEnabled) {
logger.info('=> Using React fast refresh feature.');
isDevelopment && (reactOptions.fastRefresh || process.env.FAST_REFRESH === 'true');

if (!fastRefreshEnabled) {
return config;
}

logger.info('=> Using React fast refresh feature.');
return {
...config,
module: {
...config.module,
rules: [
...config.module.rules,
fastRefreshEnabled && {
test: /\.[jt]sx?$/,
exclude: /node_modules/,
use: [
{
loader: require.resolve('babel-loader'),
options: {
plugins: [require.resolve('react-refresh/babel')],
},
},
],
},
].filter(Boolean),
},
plugins: [...config.plugins, fastRefreshEnabled && new ReactRefreshWebpackPlugin()].filter(
Boolean
),
plugins: [...(config.plugins || []), new ReactRefreshWebpackPlugin()],
};
}
3 changes: 3 additions & 0 deletions examples/cra-kitchen-sink/.storybook/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ const path = require('path');
module.exports = {
stories: ['../src/stories/**/*.stories.@(js|mdx)'],
logLevel: 'debug',
reactOptions: {
fastRefresh: true,
},
addons: [
'@storybook/preset-create-react-app',
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import React from 'react';

export const Refresh = () => {
export const FastRefreshExample = () => {
const [value, setValue] = React.useState('abc');
return (
<>
<input value={value} onChange={(event) => setValue(event.target.value)} />
<p>Change the input value then this text in the component.</p>
<p>Change the input value then this text in the component file.</p>
<p>The state of the input should be kept.</p>
</>
);
Expand Down
9 changes: 9 additions & 0 deletions examples/cra-kitchen-sink/src/stories/fast-refresh.stories.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import React from 'react';
import { FastRefreshExample } from '../components/FastRefreshExample';

export default {
title: 'React Fast Refresh',
component: FastRefreshExample,
};

export const Default = () => <FastRefreshExample />;

This file was deleted.

1 change: 1 addition & 0 deletions lib/core/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export interface StorybookOptions {
configType: 'DEVELOPMENT' | 'PRODUCTION';
presetsList: Preset[];
typescriptOptions: TypescriptOptions;
[key: string]: any;
}

/**
Expand Down
6 changes: 5 additions & 1 deletion scripts/run-e2e-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,11 @@ export const react_typescript: Parameters = {
export const cra: Parameters = {
name: 'cra',
version: 'latest',
generator: 'npx create-react-app@{{version}} {{name}}-{{version}}',
generator: [
'npx create-react-app@{{version}} {{name}}-{{version}}',
'cd {{name}}-{{version}}',
'echo "FAST_REFRESH=true" > .env',
].join(' && '),
};

export const cra_typescript: Parameters = {
Expand Down