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

fix react refresh sourcemap in dev mode #1963

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
44 changes: 44 additions & 0 deletions plugins/plugin-react-refresh/hmr-babel-plugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const fs = require('fs');

/**
* @param {import("@babel/core")} babel
* @param {{id: string|number}} options
* @returns {import("@babel/core").PluginObj}
*/
module.exports = function plugin(babel, options = {}) {
if (!options.id) {
throw new Error('id is required');
}

const reactRefreshSetup = babel.template.program(
fs.readFileSync(require.resolve('./template/reatc-refresh-setup.js'), {encoding: 'utf-8'}),
{
placeholderPattern: /^\$\$[_A-Z0-9]+\$\$$/,
preserveComments: true,
},
);

const setup = reactRefreshSetup({
$$REGISTER_ID$$: babel.types.stringLiteral(String(options.id)),
});

const connect = babel.template.program.ast(
fs.readFileSync(require.resolve('./template/reatc-refresh-connect.js'), {
encoding: 'utf-8',
}),
{
preserveComments: true,
},
);

return {
visitor: {
Program: {
exit(path) {
path.node.body.unshift(setup);
path.node.body.push(connect);
},
},
},
};
};
95 changes: 55 additions & 40 deletions plugins/plugin-react-refresh/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,67 +33,72 @@ function transformHtml(contents) {

const babel = require('@babel/core');
const IS_FAST_REFRESH_ENABLED = /\$RefreshReg\$\(/;
async function transformJs(contents, id, cwd, skipTransform) {
let fastRefreshEnhancedCode;

async function transformJs(
contents,
id,
cwd,
skipTransform,
inputSourceMap,
sourceMaps,
reactRefreshOptions,
) {
if (skipTransform) {
fastRefreshEnhancedCode = contents;
return contents;
} else if (IS_FAST_REFRESH_ENABLED.test(contents)) {
// Warn in case someone has a bad setup, and to help older users upgrade.
console.warn(
`[@snowpack/plugin-react-refresh] ${id}\n"react-refresh/babel" plugin no longer needed in your babel config, safe to remove.`,
);
fastRefreshEnhancedCode = contents;
return contents;
} else {
const {code} = await babel.transformAsync(contents, {
const {code, map} = await babel.transformAsync(contents, {
cwd,
filename: id,
ast: false,
compact: false,
sourceMaps: false,
sourceMaps,
inputSourceMap: sourceMaps && inputSourceMap ? JSON.parse(inputSourceMap) : undefined,
configFile: false,
babelrc: false,
plugins: [require('react-refresh/babel'), require('@babel/plugin-syntax-class-properties')],
plugins: [
[require('react-refresh/babel'), reactRefreshOptions],
require('@babel/plugin-syntax-class-properties'),
],
});
fastRefreshEnhancedCode = code;
}

// If fast refresh markup wasn't added, just return the original content.
if (!fastRefreshEnhancedCode || !IS_FAST_REFRESH_ENABLED.test(fastRefreshEnhancedCode)) {
return contents;
}
if (IS_FAST_REFRESH_ENABLED.test(code)) {
return babel
.transformAsync(code, {
cwd: process.cwd(),
filename: id,
ast: false,
compact: false,
sourceMaps,
inputSourceMap: (sourceMaps && map) || undefined,
configFile: false,
babelrc: false,
plugins: [[require('./hmr-babel-plugin'), {id}]],
})
.then((result) => {
if (result.map) {
return {contents: result.code, map: result.map};
}
return result.code;
});
} else {
if (map) {
return {contents: code, map};
}

return `
/** React Refresh: Setup **/
if (import.meta.hot) {
if (!window.$RefreshReg$ || !window.$RefreshSig$ || !window.$RefreshRuntime$) {
console.warn('@snowpack/plugin-react-refresh: HTML setup script not run. React Fast Refresh only works when Snowpack serves your HTML routes. You may want to remove this plugin.');
} else {
var prevRefreshReg = window.$RefreshReg$;
var prevRefreshSig = window.$RefreshSig$;
window.$RefreshReg$ = (type, id) => {
window.$RefreshRuntime$.register(type, ${JSON.stringify(id)} + " " + id);
return code;
}
window.$RefreshSig$ = window.$RefreshRuntime$.createSignatureFunctionForTransform;
}
}

${fastRefreshEnhancedCode}

/** React Refresh: Connect **/
if (import.meta.hot) {
window.$RefreshReg$ = prevRefreshReg
window.$RefreshSig$ = prevRefreshSig
import.meta.hot.accept(() => {
window.$RefreshRuntime$.performReactRefresh()
});
}`;
}

module.exports = function reactRefreshTransform(snowpackConfig, {babel}) {
module.exports = function reactRefreshTransform(snowpackConfig, {babel, reactRefreshOptions}) {
return {
name: '@snowpack/plugin-react-refresh',
transform({contents, fileExt, id, isDev}) {
transform({contents, fileExt, id, isDev, inputSourceMap}) {
// Use long-form "=== false" to handle older Snowpack versions
if (snowpackConfig.devOptions.hmr === false) {
return;
Expand All @@ -103,7 +108,17 @@ module.exports = function reactRefreshTransform(snowpackConfig, {babel}) {
}
if (fileExt === '.js') {
const skipTransform = babel === false;
return transformJs(contents, id, snowpackConfig.root || process.cwd(), skipTransform);
const sourceMaps =
snowpackConfig.buildOptions && snowpackConfig.buildOptions.sourceMaps ? true : false;
return transformJs(
contents,
id,
snowpackConfig.root || process.cwd(),
skipTransform,
inputSourceMap,
sourceMaps,
reactRefreshOptions,
);
}
if (fileExt === '.html') {
return transformHtml(contents);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/** React Refresh: Connect **/
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: spelling... reatc in this file and the next should be react

if (import.meta.hot) {
window.$RefreshReg$ = prevRefreshReg;
window.$RefreshSig$ = prevRefreshSig;
import.meta.hot.accept(() => {
window.$RefreshRuntime$.performReactRefresh();
});
}
15 changes: 15 additions & 0 deletions plugins/plugin-react-refresh/template/reatc-refresh-setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/** React Refresh: Setup **/
if (import.meta.hot) {
if (!window.$RefreshReg$ || !window.$RefreshSig$ || !window.$RefreshRuntime$) {
console.warn(
'@snowpack/plugin-react-refresh: HTML setup script not run. React Fast Refresh only works when Snowpack serves your HTML routes. You may want to remove this plugin.',
);
} else {
var prevRefreshReg = window.$RefreshReg$;
var prevRefreshSig = window.$RefreshSig$;
window.$RefreshReg$ = (type, id) => {
window.$RefreshRuntime$.register(type, $$REGISTER_ID$$ + ' ' + id);
};
window.$RefreshSig$ = window.$RefreshRuntime$.createSignatureFunctionForTransform;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1424,17 +1424,18 @@ exports.setSignature = setSignature;
exports[`@snowpack/plugin-react-refresh transform js and html: html and isDev=false 1`] = `undefined`;

exports[`@snowpack/plugin-react-refresh transform js and html: js 1`] = `
"
/** React Refresh: Setup **/
"/** React Refresh: Setup **/
if (import.meta.hot) {
if (!window.$RefreshReg$ || !window.$RefreshSig$ || !window.$RefreshRuntime$) {
console.warn('@snowpack/plugin-react-refresh: HTML setup script not run. React Fast Refresh only works when Snowpack serves your HTML routes. You may want to remove this plugin.');
} else {
var prevRefreshReg = window.$RefreshReg$;
var prevRefreshSig = window.$RefreshSig$;

window.$RefreshReg$ = (type, id) => {
window.$RefreshRuntime$.register(type, \\"stub.js\\" + \\" \\" + id);
}
window.$RefreshRuntime$.register(type, \\"stub.js\\" + ' ' + id);
};

window.$RefreshSig$ = window.$RefreshRuntime$.createSignatureFunctionForTransform;
}
}
Expand All @@ -1452,12 +1453,11 @@ var _c;

$RefreshReg$(_c, \\"App\\");

/** React Refresh: Connect **/
if (import.meta.hot) {
window.$RefreshReg$ = prevRefreshReg
window.$RefreshSig$ = prevRefreshSig
window.$RefreshReg$ = prevRefreshReg;
window.$RefreshSig$ = prevRefreshSig;
import.meta.hot.accept(() => {
window.$RefreshRuntime$.performReactRefresh()
window.$RefreshRuntime$.performReactRefresh();
});
}"
`;
Expand Down
38 changes: 3 additions & 35 deletions plugins/plugin-react-refresh/test/plugin.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
mockBabel();
const path = require('path');
const fs = require('fs');
const pluginReactRefresh = require('../plugin');
Expand All @@ -24,37 +23,6 @@ const jsTransformOptions = {
isDev: true,
};

function mockBabel() {
jest.mock('@babel/core');
const babel = require('@babel/core');
babel.transformAsync = jest
.fn()
.mockName('babel.transformAsync')
.mockImplementation(async (contents, options, ...args) => {
options.plugins = (options.plugins || []).map((plugin) => {
if (Array.isArray(plugin)) {
if (plugin[1]) {
plugin[1].skipEnvCheck = true;
}
return plugin;
}
// Fix: React Refresh Babel transform should only be enabled in development environment.
// Instead, the environment is: "test".
// If you want to override this check, pass {skipEnvCheck: true} as plugin options.
return [plugin, {skipEnvCheck: true}];
});

// Stop `jest.requireActual('@babel/core').transformAsync()` from requiring mocked babel function
jest.unmock('@babel/core');
const ret = await jest
.requireActual('@babel/core')
.transformAsync(contents, options, ...args);
mockBabel();

return ret;
});
}

async function testPluginInstance(pluginInstance) {
const pluginTransform = pluginInstance.transform;
expect(await pluginTransform(htmlTransformOptions)).toMatchSnapshot('html');
Expand All @@ -75,7 +43,7 @@ describe('@snowpack/plugin-react-refresh', () => {
hmr: true,
},
},
{babel: true},
{babel: true, reactRefreshOptions: {skipEnvCheck: true}},
);
await testPluginInstance(pluginInstance);
});
Expand All @@ -87,7 +55,7 @@ describe('@snowpack/plugin-react-refresh', () => {
hmr: false,
},
},
{babel: true},
{babel: true, reactRefreshOptions: {skipEnvCheck: true}},
);
await testPluginInstance(pluginInstance);
});
Expand All @@ -99,7 +67,7 @@ describe('@snowpack/plugin-react-refresh', () => {
hmr: true,
},
},
{babel: false},
{babel: false, reactRefreshOptions: {skipEnvCheck: true}},
);
await testPluginInstance(pluginInstance);
});
Expand Down