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

feat: set react-refresh globals on Webpack require instead of global scope #102

Merged
merged 16 commits into from
Jun 8, 2020
Merged
Show file tree
Hide file tree
Changes from 12 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
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
],
"scripts": {
"pretest": "yarn link && yarn link \"@pmmmwh/react-refresh-webpack-plugin\"",
"posttest": "yarn unlink \"@pmmmwh/react-refresh-webpack-plugin\"",
"test": "node scripts/test.js",
"lint": "eslint --report-unused-disable-directives --ext .js .",
"lint:fix": "yarn lint --fix",
Expand All @@ -47,7 +48,8 @@
"html-entities": "^1.2.1",
"lodash.debounce": "^4.0.8",
"native-url": "^0.2.6",
"schema-utils": "^2.6.5"
"schema-utils": "^2.6.5",
"source-map": "^0.7.3"
},
"devDependencies": {
"@babel/core": "^7.9.6",
Expand Down
60 changes: 0 additions & 60 deletions src/helpers/createRefreshTemplate.js

This file was deleted.

2 changes: 0 additions & 2 deletions src/helpers/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
const createRefreshTemplate = require('./createRefreshTemplate');
const getSocketIntegration = require('./getSocketIntegration');
const injectRefreshEntry = require('./injectRefreshEntry');
const normalizeOptions = require('./normalizeOptions');

module.exports = {
createRefreshTemplate,
getSocketIntegration,
injectRefreshEntry,
normalizeOptions,
Expand Down
212 changes: 164 additions & 48 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,31 @@
const path = require('path');
const validateOptions = require('schema-utils');
const webpack = require('webpack');
const {
createRefreshTemplate,
getSocketIntegration,
injectRefreshEntry,
normalizeOptions,
} = require('./helpers');
const { errorOverlay, initSocket, refreshUtils } = require('./runtime/globals');
const { DefinePlugin, ModuleFilenameHelpers, ProvidePlugin, Template } = require('webpack');
const ConstDependency = require('webpack/lib/dependencies/ConstDependency');
const NullFactory = require('webpack/lib/NullFactory');
const ParserHelpers = require('webpack/lib/ParserHelpers');
const { getSocketIntegration, injectRefreshEntry, normalizeOptions } = require('./helpers');
const schema = require('./options.json');

const refreshObj = '__webpack_require__.$Refresh$';

// Mapping of react-refresh globals to Webpack require extensions
const PARSER_REPLACEMENTS = {
$RefreshRuntime$: `${refreshObj}.runtime`,
$RefreshSetup$: `${refreshObj}.setup`,
$RefreshCleanup$: `${refreshObj}.cleanup`,
$RefreshReg$: `${refreshObj}.register`,
$RefreshSig$: `${refreshObj}.signature`,
};

const PARSER_REPLACEMENT_TYPES = {
$RefreshRuntime$: 'object',
$RefreshSetup$: 'function',
$RefreshCleanup$: 'function',
$RefreshReg$: 'function',
$RefreshSig$: 'function',
};

class ReactRefreshPlugin {
/**
* @param {import('./types').ReactRefreshPluginOptions} [options] Options for react-refresh-plugin.
Expand Down Expand Up @@ -49,24 +65,24 @@ class ReactRefreshPlugin {
// Inject react-refresh context to all Webpack entry points
compiler.options.entry = injectRefreshEntry(compiler.options.entry, this.options);

// Inject necessary modules to Webpack's global scope
// Inject necessary modules to bundle's global scope
let providedModules = {
[refreshUtils]: require.resolve('./runtime/refreshUtils'),
__react_refresh_utils__: require.resolve('./runtime/refreshUtils'),
};

if (this.options.overlay === false) {
// Stub errorOverlay module so calls to it will be erased
const definePlugin = new webpack.DefinePlugin({ [errorOverlay]: false });
const definePlugin = new DefinePlugin({ __react_refresh_error_overlay__: false });
definePlugin.apply(compiler);
} else {
providedModules = {
...providedModules,
[errorOverlay]: require.resolve(this.options.overlay.module),
[initSocket]: getSocketIntegration(this.options.overlay.sockIntegration),
__react_refresh_error_overlay__: require.resolve(this.options.overlay.module),
__react_refresh_init_socket__: getSocketIntegration(this.options.overlay.sockIntegration),
};
}

const providePlugin = new webpack.ProvidePlugin(providedModules);
const providePlugin = new ProvidePlugin(providedModules);
providePlugin.apply(compiler);

compiler.hooks.beforeRun.tap(this.constructor.name, (compiler) => {
Expand All @@ -86,7 +102,7 @@ class ReactRefreshPlugin {
}
});

const matchObject = webpack.ModuleFilenameHelpers.matchObject.bind(undefined, this.options);
const matchObject = ModuleFilenameHelpers.matchObject.bind(undefined, this.options);
compiler.hooks.normalModuleFactory.tap(this.constructor.name, (nmf) => {
nmf.hooks.afterResolve.tap(this.constructor.name, (data) => {
// Inject refresh loader to all JavaScript-like files
Expand All @@ -108,43 +124,143 @@ class ReactRefreshPlugin {
});
});

compiler.hooks.compilation.tap(this.constructor.name, (compilation) => {
compilation.mainTemplate.hooks.require.tap(
this.constructor.name,
// Constructs the correct module template for react-refresh
(source, chunk, hash) => {
const mainTemplate = compilation.mainTemplate;

// Check for the output filename
// This is to ensure we are processing a JS-related chunk
let filename = mainTemplate.outputOptions.filename;
if (typeof filename === 'function') {
// Only usage of the `chunk` property is documented by Webpack.
// However, some internal Webpack plugins uses other properties,
// so we also pass them through to be on the safe side.
filename = filename({
chunk,
hash,
// TODO: Figure out whether we need to stub the following properties, probably no
contentHashType: 'javascript',
hashWithLength: (length) => mainTemplate.renderCurrentHashCode(hash, length),
noChunkHash: mainTemplate.useChunkHash(chunk),
});
compiler.hooks.compilation.tap(
this.constructor.name,
(compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());

compilation.mainTemplate.hooks.require.tap(
this.constructor.name,
// Constructs the module template for react-refresh
(source, chunk, hash) => {
const mainTemplate = compilation.mainTemplate;

// Check for the output filename
// This is to ensure we are processing a JS-related chunk
let filename = mainTemplate.outputOptions.filename;
if (typeof filename === 'function') {
// Only usage of the `chunk` property is documented by Webpack.
// However, some internal Webpack plugins uses other properties,
// so we also pass them through to be on the safe side.
filename = filename({
chunk,
hash,
// TODO: Figure out whether we need to stub the following properties, probably no
contentHashType: 'javascript',
hashWithLength: (length) => mainTemplate.renderCurrentHashCode(hash, length),
noChunkHash: mainTemplate.useChunkHash(chunk),
});
}

// Check whether the current compilation is outputting to JS,
// since other plugins can trigger compilations for other file types too.
// If we apply the transform to them, their compilation will break fatally.
// One prominent example of this is the HTMLWebpackPlugin.
// If filename is falsy, something is terribly wrong and there's nothing we can do.
if (!filename || !filename.includes('.js')) {
return source;
}

// Split template source code into lines for easier processing
const lines = source.split('\n');
// Webpack generates this line when the MainTemplate is called
const moduleInitializationLineNumber = lines.findIndex((line) =>
line.startsWith('modules[moduleId].call')
);

return Template.asString([
...lines.slice(0, moduleInitializationLineNumber),
'',
`${refreshObj}.setup = function(currentModuleId) {`,
Template.indent([
`const prevSetup = ${refreshObj}.setup;`,
`const prevCleanup = ${refreshObj}.cleanup;`,
`const prevReg = ${refreshObj}.register;`,
`const prevSig = ${refreshObj}.signature;`,
'',
`${refreshObj}.register = function register(type, id) {`,
Template.indent([
'const typeId = currentModuleId + " " + id;',
`${refreshObj}.runtime.register(type, typeId);`,
]),
'};',
'',
`${refreshObj}.signature = ${refreshObj}.runtime.createSignatureFunctionForTransform;`,
'',
`${refreshObj}.cleanup = function cleanup() {`,
Template.indent([
`${refreshObj}.register = prevReg;`,
`${refreshObj}.signature = prevSig;`,
`${refreshObj}.cleanup = prevCleanup;`,
]),
'};',
'',
`${refreshObj}.setup = prevSetup;`,
]),
'};',
'',
'try {',
Template.indent(lines[moduleInitializationLineNumber]),
'} finally {',
Template.indent(`${refreshObj}.cleanup();`),
'}',
'',
...lines.slice(moduleInitializationLineNumber + 1, lines.length),
]);
}
);

// Check whether the current compilation is outputting to JS,
// since other plugins can trigger compilations for other file types too.
// If we apply the transform to them, their compilation will break fatally.
// One prominent example of this is the HTMLWebpackPlugin.
// If filename is falsy, something is terribly wrong and there's nothing we can do.
if (!filename || !filename.includes('.js')) {
return source;
compilation.mainTemplate.hooks.requireExtensions.tap(
this.constructor.name,
// Setup react-refresh globals as extensions to Webpack's require function
(source) => {
return Template.asString([
source,
'',
`${refreshObj} = {};`,
`${refreshObj}.runtime = {};`,
`${refreshObj}.setup = function() {};`,
`${refreshObj}.cleanup = function() {};`,
`${refreshObj}.register = function() {};`,
`${refreshObj}.signature = function() {`,
Template.indent('return function(type) { return type; };'),
'};',
]);
}
);

return createRefreshTemplate(source);
}
);
});
// Transform global calls into require extensions calls
const parserHandler = (parser) => {
Object.entries(PARSER_REPLACEMENTS).forEach(([key, replacement]) => {
parser.hooks.expression
.for(key)
.tap(
this.constructor.name,
ParserHelpers.toConstantDependencyWithWebpackRequire(parser, replacement)
);
if (PARSER_REPLACEMENT_TYPES[key]) {
parser.hooks.evaluateTypeof
.for(key)
.tap(
this.constructor.name,
ParserHelpers.evaluateToString(PARSER_REPLACEMENT_TYPES[key])
);
}
});
};

normalModuleFactory.hooks.parser
.for('javascript/auto')
.tap(this.constructor.name, parserHandler);
normalModuleFactory.hooks.parser
.for('javascript/dynamic')
.tap(this.constructor.name, parserHandler);
normalModuleFactory.hooks.parser
.for('javascript/esm')
.tap(this.constructor.name, parserHandler);
}
);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* global $RefreshUtils$ */
/* global __react_refresh_utils__ */

/**
* Code injected to each JS-like module for react-refresh capabilities.
* Code appended to each JS-like module for react-refresh capabilities.
*
* `$RefreshUtils$` is replaced to the actual utils during source parsing by `webpack.ProvidePlugin`.
*
Expand All @@ -11,29 +11,29 @@
* [Reference for HMR Error Recovery](https://github.com/webpack/webpack/issues/418#issuecomment-490296365)
*/
module.exports = function () {
const currentExports = $RefreshUtils$.getModuleExports(module);
$RefreshUtils$.registerExportsForReactRefresh(currentExports, module.id);
const currentExports = __react_refresh_utils__.getModuleExports(module);
__react_refresh_utils__.registerExportsForReactRefresh(currentExports, module.id);

if (module.hot) {
const isHotUpdate = !!module.hot.data;
const prevExports = isHotUpdate ? module.hot.data.prevExports : null;

if ($RefreshUtils$.isReactRefreshBoundary(currentExports)) {
module.hot.dispose($RefreshUtils$.createHotDisposeCallback(currentExports));
module.hot.accept($RefreshUtils$.createHotErrorHandler(module.id));
if (__react_refresh_utils__.isReactRefreshBoundary(currentExports)) {
module.hot.dispose(__react_refresh_utils__.createHotDisposeCallback(currentExports));
module.hot.accept(__react_refresh_utils__.createHotErrorHandler(module.id));

if (isHotUpdate) {
if (
$RefreshUtils$.isReactRefreshBoundary(prevExports) &&
$RefreshUtils$.shouldInvalidateReactRefreshBoundary(prevExports, currentExports)
__react_refresh_utils__.isReactRefreshBoundary(prevExports) &&
__react_refresh_utils__.shouldInvalidateReactRefreshBoundary(prevExports, currentExports)
) {
module.hot.invalidate();
} else {
$RefreshUtils$.enqueueUpdate();
__react_refresh_utils__.enqueueUpdate();
}
}
} else {
if (isHotUpdate && $RefreshUtils$.isReactRefreshBoundary(prevExports)) {
if (isHotUpdate && __react_refresh_utils__.isReactRefreshBoundary(prevExports)) {
module.hot.invalidate();
}
}
Expand Down
Loading