Skip to content

Commit

Permalink
Client/Socket - ESM conversion (#342)
Browse files Browse the repository at this point in the history
  • Loading branch information
pmmmwh authored Apr 3, 2021
1 parent 38e70c0 commit 6e35c67
Show file tree
Hide file tree
Showing 24 changed files with 216 additions and 301 deletions.
7 changes: 7 additions & 0 deletions .babelrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"env": {
"test": {
"plugins": ["@babel/plugin-transform-modules-commonjs"]
}
}
}
14 changes: 6 additions & 8 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,10 @@
},
"overrides": [
{
"files": [
"client/**/*.js",
"overlay/**/*.js",
"lib/runtime/**/*.js",
"loader/*.runtime.js",
"sockets/**/*.js"
],
"files": ["client/**/*.js", "overlay/**/*.js", "lib/runtime/**/*.js", "sockets/**/*.js"],
"parserOptions": {
"ecmaVersion": 2015
"ecmaVersion": 2015,
"sourceType": "module"
},
"env": {
"browser": true,
Expand All @@ -39,6 +34,9 @@
"__DEBUG__": true,
"WEBPACK_VERSION": true,
"browser": true
},
"parserOptions": {
"sourceType": "module"
}
},
{
Expand Down
16 changes: 8 additions & 8 deletions client/ErrorOverlayEntry.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/* global __react_refresh_error_overlay__, __react_refresh_init_socket__, __resourceQuery */
/* global __react_refresh_error_overlay__, __react_refresh_socket__, __resourceQuery */

const errorEventHandlers = require('./utils/errorEventHandlers');
const formatWebpackErrors = require('./utils/formatWebpackErrors');
const runWithPatchedUrl = require('./utils/patchUrl');
import { handleError, handleUnhandledRejection } from './utils/errorEventHandlers.js';
import formatWebpackErrors from './utils/formatWebpackErrors.js';
import runWithPatchedUrl from './utils/patchUrl.js';

// Setup error states
let isHotReload = false;
Expand Down Expand Up @@ -34,7 +34,7 @@ function handleCompileSuccess() {

/**
* A function called after a compile errored signal is received from Webpack.
* @param {string} errors
* @param {string[]} errors
* @returns {void}
*/
function handleCompileErrors(errors) {
Expand Down Expand Up @@ -76,13 +76,13 @@ if (process.env.NODE_ENV !== 'production' && typeof window !== 'undefined') {
// Only register if no other overlay have been registered
if (!window.__reactRefreshOverlayInjected) {
// Registers handlers for compile errors
__react_refresh_init_socket__(compileMessageHandler, __resourceQuery);
__react_refresh_socket__.init(compileMessageHandler, __resourceQuery);
// Registers handlers for runtime errors
errorEventHandlers.error(function handleError(error) {
handleError(function handleError(error) {
hasRuntimeErrors = true;
__react_refresh_error_overlay__.handleRuntimeError(error);
});
errorEventHandlers.unhandledRejection(function handleUnhandledPromiseRejection(error) {
handleUnhandledRejection(function handleUnhandledPromiseRejection(error) {
hasRuntimeErrors = true;
__react_refresh_error_overlay__.handleRuntimeError(error);
});
Expand Down
2 changes: 1 addition & 1 deletion client/LegacyWDSSocketEntry.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const SockJS = require('sockjs-client/dist/sockjs');
import * as SockJS from 'sockjs-client/dist/sockjs.js';

/**
* A SockJS client adapted for use with webpack-dev-server.
Expand Down
6 changes: 3 additions & 3 deletions client/ReactRefreshEntry.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
/* global __react_refresh_library__ */

const safeThis = require('./utils/safeThis');
import safeThis from 'core-js-pure/features/global-this';
import * as RefreshRuntime from 'react-refresh/runtime';

if (process.env.NODE_ENV !== 'production' && typeof safeThis !== 'undefined') {
let $RefreshInjected$ = '__reactRefreshInjected';
var $RefreshInjected$ = '__reactRefreshInjected';
// Namespace the injected flag (if necessary) for monorepo compatibility
if (typeof __react_refresh_library__ !== 'undefined' && __react_refresh_library__) {
$RefreshInjected$ += '_' + __react_refresh_library__;
}

// Only inject the runtime if it hasn't been injected
if (!safeThis[$RefreshInjected$]) {
const RefreshRuntime = require('react-refresh/runtime');
// Inject refresh runtime into global scope
RefreshRuntime.injectIntoGlobalHook(safeThis);

Expand Down
9 changes: 5 additions & 4 deletions client/utils/errorEventHandlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ function createWindowEventHandler(eventType, createHandler) {
return register;
}

module.exports = {
error: createWindowEventHandler('error', createErrorHandler),
unhandledRejection: createWindowEventHandler('unhandledrejection', createRejectionHandler),
};
export const handleError = createWindowEventHandler('error', createErrorHandler);
export const handleUnhandledRejection = createWindowEventHandler(
'unhandledrejection',
createRejectionHandler
);
3 changes: 2 additions & 1 deletion client/utils/formatWebpackErrors.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,12 @@ function formatWebpackErrors(errors) {
// Webpack 4 compilation errors are strings
return formatMessage(errorObjOrMessage);
});

if (formattedErrors.some(isLikelyASyntaxError)) {
// If there are any syntax errors, show just them.
formattedErrors = formattedErrors.filter(isLikelyASyntaxError);
}
return formattedErrors;
}

module.exports = formatWebpackErrors;
export default formatWebpackErrors;
10 changes: 4 additions & 6 deletions client/utils/patchUrl.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
/* global __react_refresh_polyfill_url__ */
import SafeURL from 'core-js-pure/web/url';
import SafeURLSearchParams from 'core-js-pure/web/url-search-params';

/**
* @typedef {Object} UrlAPIs
Expand All @@ -11,20 +13,16 @@
* @param {function(UrlAPIs): void} callback The code to run with patched URL globals.
* @returns {void}
*/
function runWithURLPatch(callback) {
function runWithPatchedUrl(callback) {
let __originalURL;
let __originalURLSearchParams;

// Polyfill the DOM URL and URLSearchParams constructors
if (__react_refresh_polyfill_url__ || !window.URL) {
const SafeURL = require('core-js-pure/web/url');

__originalURL = window.URL;
window.URL = SafeURL;
}
if (__react_refresh_polyfill_url__ || !window.URLSearchParams) {
const SafeURLSearchParams = require('core-js-pure/web/url-search-params');

__originalURLSearchParams = window.URLSearchParams;
window.URLSearchParams = SafeURLSearchParams;
}
Expand All @@ -41,4 +39,4 @@ function runWithURLPatch(callback) {
}
}

module.exports = runWithURLPatch;
export default runWithPatchedUrl;
19 changes: 0 additions & 19 deletions client/utils/safeThis.js

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const RuntimeGlobals = require('webpack/lib/RuntimeGlobals');
const RuntimeModule = require('webpack/lib/RuntimeModule');
const Template = require('webpack/lib/Template');
const { refreshGlobal } = require('../globals');
const getRefreshGlobal = require('../utils/getRefreshGlobal');
const { refreshGlobal } = require('./globals');
const { getRefreshGlobal } = require('./utils');

class ReactRefreshRuntimeModule extends RuntimeModule {
constructor() {
Expand Down
6 changes: 3 additions & 3 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,8 @@ class ReactRefreshPlugin {
if (this.options.overlay === false) {
// Stub errorOverlay module so their calls can be erased
definedModules.__react_refresh_error_overlay__ = false;
definedModules.__react_refresh_init_socket__ = false;
definedModules.__react_refresh_polyfill_url__ = false;
definedModules.__react_refresh_socket__ = false;
} else {
definedModules.__react_refresh_polyfill_url__ = this.options.overlay.useURLPolyfill || false;

Expand All @@ -106,7 +106,7 @@ class ReactRefreshPlugin {
);
}
if (this.options.overlay.sockIntegration) {
providedModules.__react_refresh_init_socket__ = getSocketIntegration(
providedModules.__react_refresh_socket__ = getSocketIntegration(
this.options.overlay.sockIntegration
);
}
Expand Down Expand Up @@ -233,7 +233,7 @@ class ReactRefreshPlugin {
case 5: {
const NormalModule = require('webpack/lib/NormalModule');
const RuntimeGlobals = require('webpack/lib/RuntimeGlobals');
const ReactRefreshRuntimeModule = require('./runtime/RefreshRuntimeModule');
const ReactRefreshRuntimeModule = require('./RefreshRuntimeModule');

compilation.hooks.additionalTreeRuntimeRequirements.tap(
this.constructor.name,
Expand Down
8 changes: 5 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@
"source-map": "^0.7.3"
},
"devDependencies": {
"@babel/core": "^7.11.6",
"@babel/core": "^7.13.14",
"@babel/plugin-transform-modules-commonjs": "^7.13.8",
"@types/cross-spawn": "^6.0.2",
"@types/fs-extra": "^9.0.4",
"@types/jest": "^26.0.15",
Expand All @@ -68,6 +69,7 @@
"@types/node": "^14.11.1",
"@types/puppeteer": "^5.4.0",
"@types/webpack": "^4.41.22",
"babel-jest": "^26.6.3",
"babel-loader": "^8.1.0",
"cross-spawn": "^7.0.3",
"del-cli": "^3.0.1",
Expand All @@ -92,11 +94,11 @@
"typescript": "4.2.2",
"webpack": "^4.44.2",
"webpack-cli": "^3.3.12",
"webpack-cli.latest": "npm:webpack-cli@^4.5.0",
"webpack-cli.latest": "npm:webpack-cli@4.x",
"webpack-dev-server": "^3.11.0",
"webpack-hot-middleware": "^2.25.0",
"webpack-plugin-serve": "^1.0.1",
"webpack.latest": "npm:webpack@^5.24.2",
"webpack.latest": "npm:webpack@5.x",
"yn": "^4.0.0"
},
"peerDependencies": {
Expand Down
6 changes: 3 additions & 3 deletions sockets/WDSSocket.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* global __webpack_dev_server_client__ */

const url = require('native-url');
const getSocketUrlParts = require('./utils/getSocketUrlParts');
import * as url from 'native-url';
import getSocketUrlParts from './utils/getSocketUrlParts.js';

/**
* Initializes a socket server for HMR for webpack-dev-server.
Expand All @@ -23,4 +23,4 @@ function initWDSSocket(messageHandler, resourceQuery) {
}
}

module.exports = initWDSSocket;
export const init = initWDSSocket;
4 changes: 2 additions & 2 deletions sockets/WHMEventSource.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const singletonKey = '__webpack_hot_middleware_reporter__';
* @returns {void}
*/
function initWHMEventSource(messageHandler) {
const client = window[singletonKey] || require('webpack-hot-middleware/client');
const client = window[singletonKey];

client.useCustomOverlay({
showProblems: function showProblems(type, data) {
Expand All @@ -28,4 +28,4 @@ function initWHMEventSource(messageHandler) {
});
}

module.exports = initWHMEventSource;
export const init = initWHMEventSource;
4 changes: 2 additions & 2 deletions sockets/WPSSocket.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* global ʎɐɹɔosǝʌɹǝs */
import { ClientSocket } from 'webpack-plugin-serve/lib/client/ClientSocket.js';

/**
* Initializes a socket server for HMR for webpack-plugin-serve.
Expand All @@ -20,7 +21,6 @@ function initWPSSocket(messageHandler) {
return;
}

const { ClientSocket } = require('webpack-plugin-serve/lib/client/ClientSocket');
const { address, client = {}, secure } = options;
const protocol = secure ? 'wss' : 'ws';
const socket = new ClientSocket(client, protocol + '://' + (client.address || address) + '/wps');
Expand Down Expand Up @@ -48,4 +48,4 @@ function initWPSSocket(messageHandler) {
});
}

module.exports = initWPSSocket;
export const init = initWPSSocket;
2 changes: 1 addition & 1 deletion sockets/utils/getCurrentScriptSource.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@ function getCurrentScriptSource() {
}
}

module.exports = getCurrentScriptSource;
export default getCurrentScriptSource;
6 changes: 3 additions & 3 deletions sockets/utils/getSocketUrlParts.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const getCurrentScriptSource = require('./getCurrentScriptSource');
const parseQuery = require('./parseQuery');
import getCurrentScriptSource from './getCurrentScriptSource.js';
import parseQuery from './parseQuery.js';

/**
* @typedef {Object} SocketUrlParts
Expand Down Expand Up @@ -108,4 +108,4 @@ function getSocketUrlParts(resourceQuery) {
};
}

module.exports = getSocketUrlParts;
export default getSocketUrlParts;
2 changes: 1 addition & 1 deletion sockets/utils/parseQuery.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@ function parseQuery(querystring) {
}, {});
}

module.exports = parseQuery;
export default parseQuery;
17 changes: 15 additions & 2 deletions test/loader/loader.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -650,7 +650,14 @@ describe('loader', () => {
/***/ })
},
0,[[\\"./index.js\\",\\"runtime\\",\\"defaultVendors\\"]]]);"
/******/ __webpack_require__ => { // webpackRuntimeModules
/******/ \\"use strict\\";
/******/
/******/ var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
/******/ __webpack_require__.O(0, [\\"defaultVendors\\"], () => (__webpack_exec__(\\"./index.js\\")));
/******/ var __webpack_exports__ = __webpack_require__.O();
/******/ }
]);"
`);

expect(compilation.errors).toStrictEqual([]);
Expand Down Expand Up @@ -861,7 +868,13 @@ describe('loader', () => {
/***/ })
},
0,[[\\"./index.js\\",\\"runtime\\"]]]);"
/******/ __webpack_require__ => { // webpackRuntimeModules
/******/ \\"use strict\\";
/******/
/******/ var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
/******/ var __webpack_exports__ = (__webpack_exec__(\\"./index.js\\"));
/******/ }
]);"
`);

expect(compilation.errors).toStrictEqual([]);
Expand Down
2 changes: 1 addition & 1 deletion test/mocks/location.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@ const mockLocation = (href) => {
return [locationMock, mockRestore];
};

module.exports = mockLocation;
export default mockLocation;
2 changes: 1 addition & 1 deletion test/unit/getRefreshGlobal.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ describe('getRefreshGlobal', () => {
() => {
const RuntimeTemplate = require('webpack/lib/RuntimeTemplate');
const refreshGlobalTemplate = getRefreshGlobal(
new RuntimeTemplate({ environment: { arrowFunction: true, const: true } }, (i) => i)
new RuntimeTemplate({}, { environment: { arrowFunction: true, const: true } }, (i) => i)
);
expect(refreshGlobalTemplate).toMatchInlineSnapshot(`
"__webpack_require__.$Refresh$ = {
Expand Down
6 changes: 3 additions & 3 deletions test/unit/getSocketUrlParts.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@

jest.mock('../../sockets/utils/getCurrentScriptSource');

const getCurrentScriptSource = require('../../sockets/utils/getCurrentScriptSource');
const getSocketUrlParts = require('../../sockets/utils/getSocketUrlParts');
const mockLocation = require('../mocks/location');
import getCurrentScriptSource from '../../sockets/utils/getCurrentScriptSource';
import getSocketUrlParts from '../../sockets/utils/getSocketUrlParts';
import mockLocation from '../mocks/location';

describe('getSocketUrlParts', () => {
beforeEach(() => {
Expand Down
Loading

0 comments on commit 6e35c67

Please sign in to comment.