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

Upgrade webpack to v5 #128

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
"ws": "^7.2.0"
},
"peerDependencies": {
"webpack": "^4"
"webpack": "^5.36.2"
},
"devDependencies": {
"@babel/core": "^7.6.4",
Expand All @@ -83,7 +83,7 @@
"autoprefixer": "^9.6.5",
"babel-loader": "^8.0.6",
"chai": "^4.2.0",
"copy-webpack-plugin": "^5.0.4",
"copy-webpack-plugin": "^8.1.1",
"css-loader": "^3.2.0",
"husky": "^3.0.9",
"json-loader": "^0.5.7",
Expand All @@ -99,8 +99,8 @@
"tslint": "^5.20.1",
"tslint-config-prettier": "^1.18.0",
"typescript": "^3.7.2",
"webpack": "^4.41.2",
"webpack": "5.36.2",
"webpack-bundle-analyzer": "^3.6.0",
"webpack-cli": "^3.3.9"
"webpack-cli": "^4.6.0"
}
}
26 changes: 14 additions & 12 deletions src/ExtensionReloader.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { merge } from "lodash";
import { Compiler, Entry, Output, version } from "webpack";
import { Compiler, Compilation, Chunk, Entry, version } from "webpack";
import { changesTriggerer } from "./hot-reload";
import { onlyOnDevelopmentMsg } from "./messages/warnings";
import { middlewareInjector } from "./middleware";
Expand Down Expand Up @@ -35,14 +35,16 @@ export default class ExtensionReloaderImpl extends AbstractPluginReloader
}

public _whatChanged(
chunks: IWebpackChunk[],
chunks: Compilation["chunks"],
{ background, contentScript, extensionPage }: IEntriesOption,
) {
const changedChunks = chunks.filter(({ name, hash }) => {
const oldVersion = this._chunkVersions[name];
this._chunkVersions[name] = hash;
return hash !== oldVersion;
});
const changedChunks = [] as Chunk[];

for (const chunk of chunks) {
const oldVersion = this._chunkVersions[chunk.name];
this._chunkVersions[chunk.name] = chunk.hash;
if (chunk.hash !== oldVersion) changedChunks.push(chunk);
}

const contentOrBgChanged = changedChunks.some(({ name }) => {
let contentChanged = false;
Expand All @@ -57,6 +59,7 @@ export default class ExtensionReloaderImpl extends AbstractPluginReloader
return contentChanged || bgChanged;
});

//
const onlyPageChanged =
!contentOrBgChanged &&
changedChunks.some(({ name }) => {
Expand All @@ -67,6 +70,7 @@ export default class ExtensionReloaderImpl extends AbstractPluginReloader
} else {
pageChanged = name === extensionPage;
}
//

return pageChanged;
});
Expand All @@ -83,7 +87,7 @@ export default class ExtensionReloaderImpl extends AbstractPluginReloader
const parsedEntries: IEntriesOption = manifest
? extractEntries(
compiler.options.entry as Entry,
compiler.options.output as Output,
compiler.options.output as Compiler["options"]["output"],
manifest,
)
: entries;
Expand All @@ -98,16 +102,14 @@ export default class ExtensionReloaderImpl extends AbstractPluginReloader
};
});

this._eventAPI.afterEmit((comp, done) => {
this._eventAPI.afterEmit(comp => {
const { contentOrBgChanged, onlyPageChanged } = this._whatChanged(
comp.chunks,
parsedEntries,
);

if (contentOrBgChanged || onlyPageChanged) {
this._triggerer(onlyPageChanged)
.then(done)
.catch(done);
this._triggerer(onlyPageChanged);
}
});
}
Expand Down
2 changes: 1 addition & 1 deletion src/hot-reload/SignEmitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default class SignEmitter {
private _safeSignChange: (
reloadPage: boolean,
onlyPageChanged: boolean,
onSuccess: () => void,
onSuccess: (val?: any) => void,
onError: (err: Error) => void,
) => void;
private _server: Server;
Expand Down
6 changes: 4 additions & 2 deletions src/middleware/middleware-injector.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Compilation } from "webpack";
import { ConcatSource, Source } from "webpack-sources";
import { SourceFactory } from "../../typings";
import middleWareSourceBuilder from "./middleware-source-builder";
Expand All @@ -17,10 +18,11 @@ const middlewareInjector: MiddlewareInjector = (
name === extensionPage ||
(extensionPage && extensionPage.includes(name));

return (assets, chunks) =>
chunks.reduce((prev, { name, files }) => {
return (assets, chunks: Compilation["chunks"]) =>
Array.from(chunks).reduce((prev, { name, files }) => {
if (matchBgOrContentOrPage(name)) {
files.forEach(entryPoint => {
console.log(`Entry point: ${entryPoint}`);
if (/\.js$/.test(entryPoint)) {
const finalSrc = sourceFactory(source, assets[entryPoint]);
prev[entryPoint] = finalSrc;
Expand Down
14 changes: 8 additions & 6 deletions src/middleware/wer-middleware.raw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
/* external argument must be provided using it */
/* -------------------------------------------------- */
(function(window) {

const injectionContext = window || this || {browser: null};

const injectionContext = {browser: null};
(function() {
`<%= polyfillSource %>`;
}).bind(injectionContext)();

const { browser }: any = injectionContext;
const { browser }: any = injectionContext || {};
const signals: any = JSON.parse('<%= signals %>');
const config: any = JSON.parse('<%= config %>');

Expand All @@ -27,7 +28,7 @@
} = signals;
const { RECONNECT_INTERVAL, SOCKET_ERR_CODE_REF } = config;

const { extension, runtime, tabs } = browser;
const { extension, runtime, tabs } = browser || {};
const manifest = runtime.getManifest();

// =============================== Helper functions ======================================= //
Expand All @@ -38,9 +39,10 @@

// ========================== Called only on content scripts ============================== //
function contentScriptWorker() {
console.log('contentScriptWorker')
runtime.sendMessage({ type: SIGN_CONNECT }).then(msg => console.info(msg));

runtime.onMessage.addListener(({ type, payload }: IAction) => {
runtime.onMessage.addListener(({ type, payload }: { type: string; payload: any }) => {
switch (type) {
case SIGN_RELOAD:
logger("Detected Changes. Reloading ...");
Expand All @@ -56,7 +58,7 @@

// ======================== Called only on background scripts ============================= //
function backgroundWorker(socket: WebSocket) {
runtime.onMessage.addListener((action: IAction, sender) => {
runtime.onMessage.addListener((action: { type: string; payload: any }, sender) => {
if (action.type === SIGN_CONNECT) {
return Promise.resolve(formatter("Connected to Extension Hot Reloader"));
}
Expand Down Expand Up @@ -114,7 +116,7 @@
function extensionPageWorker() {
runtime.sendMessage({ type: SIGN_CONNECT }).then(msg => console.info(msg));

runtime.onMessage.addListener(({ type, payload }: IAction) => {
runtime.onMessage.addListener(({ type, payload }: { type: string; payload: any }) => {
switch (type) {
case SIGN_CHANGE:
logger("Detected Changes. Reloading ...");
Expand Down
4 changes: 2 additions & 2 deletions src/utils/manifest.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { readFileSync } from "fs";
import { flatMapDeep } from "lodash";
import { Entry, Output } from "webpack";
import { Compiler, Entry } from "webpack";
import {
bgScriptEntryErrorMsg,
bgScriptManifestRequiredMsg,
} from "../messages/errors";

export function extractEntries(
webpackEntry: Entry,
webpackOutput: Output = {},
webpackOutput: Compiler["options"]["output"] = {},
manifestPath: string,
): IEntriesOption {
const manifestJson = JSON.parse(
Expand Down
4 changes: 2 additions & 2 deletions src/webpack/AbstractExtensionReloader.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Compiler, Plugin } from "webpack";
import { Compiler } from "webpack";
import CompilerEventsFacade from "./CompilerEventsFacade";

export default abstract class AbstractExtensionReloader implements Plugin {
export default abstract class AbstractExtensionReloader {
public context: any;
protected _injector: InjectMiddleware;
protected _triggerer: Triggerer;
Expand Down
14 changes: 8 additions & 6 deletions src/webpack/CompilerEventsFacade.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
import { Compiler } from "webpack";
import { Compiler, Compilation } from "webpack";

export default class CompilerEventsFacade {
public static extensionName = "webpack-extension-reloader";
private _compiler: Compiler;
private _legacyTapable: boolean;

constructor(compiler) {
constructor(compiler: Compiler) {
this._compiler = compiler;
this._legacyTapable = !compiler.hooks;
}

public afterOptimizeChunkAssets(call) {
public afterOptimizeChunkAssets(
call: (compilation: Compilation, chunks: Compilation["chunks"]) => void,
) {
return this._legacyTapable
? this._compiler.plugin("compilation", comp =>
? (this._compiler as any).plugin("compilation", comp =>
comp.plugin("after-optimize-chunk-assets", chunks =>
call(comp, chunks),
),
Expand All @@ -27,9 +29,9 @@ export default class CompilerEventsFacade {
);
}

public afterEmit(call) {
public afterEmit(call: (compilation: Compilation) => void) {
return this._legacyTapable
? this._compiler.plugin("after-emit", call)
? (this._compiler as any).plugin("after-emit", call)
: this._compiler.hooks.afterEmit.tap(
CompilerEventsFacade.extensionName,
call,
Expand Down
2 changes: 1 addition & 1 deletion typings/declarations.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ declare interface IMiddlewareTemplateParams {

declare type InjectMiddleware = (
assets: Record<string, any>,
chunks: IWebpackChunk[],
chunks: Set<any>,
) => Record<string, any>;

declare type MiddlewareInjector = (
Expand Down
30 changes: 15 additions & 15 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,66 +12,66 @@ module.exports = (env = { analyze: false }) => ({
target: "node",
entry: test({ tests: "./specs/index.ts" }) || {
[packName]: "./src/index.ts",
[`${packName}-cli`]: "./client/index.ts"
[`${packName}-cli`]: "./client/index.ts",
},
devtool: "inline-source-map",
output: {
publicPath: ".",
path: path.resolve(__dirname, "./dist"),
filename: "[name].js",
libraryTarget: "umd"
libraryTarget: "umd",
},
plugins: [
env.analyze && isProduction(new BundleAnalyzerPlugin({ sourceMap: true })),
new BannerPlugin({
banner: `/// <reference path="../typings/${packName}.d.ts" />`,
raw: true,
entryOnly: true,
include: "webpack-extension-reloader"
include: "webpack-extension-reloader",
}),
new BannerPlugin({
banner: "#!/usr/bin/env node",
raw: true,
entryOnly: true,
include: `${packName}-cli`
})
include: `${packName}-cli`,
}),
].filter(plugin => !!plugin),
externals: [
...Object.keys(pack.dependencies),
"webpack",
"webpack-extension-reloader"
"webpack-extension-reloader",
],
resolve: {
modules: [path.resolve(__dirname, "src"), "node_modules"],
mainFiles: ["index"],
extensions: [".ts", ".tsx", ".js"]
extensions: [".ts", ".tsx", ".js"],
},
optimization: {
minimize: false,
nodeEnv: false
nodeEnv: false,
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ["babel-loader"]
loader: "babel-loader",
},
{
test: /\.tsx?$/,
exclude: /node_modules/,
loaders: ["babel-loader", "ts-loader"]
use: ["babel-loader", "ts-loader"],
},
{
test: /\.json$/,
exclude: /node_modules/,
loaders: ["json-loader"]
loader: "json-loader",
},
{
test: /\.txt$/,
exclude: /node_modules/,
loaders: ["raw-loader"]
}
]
}
loader: "raw-loader",
},
],
},
});