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

Create Plugin: Introduce experimental Rspack feature flag #1564

Open
wants to merge 11 commits into
base: main
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
11 changes: 11 additions & 0 deletions packages/create-plugin/src/commands/generate.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,17 @@ function getActionsForTemplateFolder({
files = files.filter((file) => path.basename(file) !== 'npmrc');
}

// filter out frontend bundler based on user choice
files = files.filter((file) => {
if (file.includes('webpack') && templateData.useExperimentalRspack) {
return false;
}
if (file.includes('rspack') && !templateData.useExperimentalRspack) {
return false;
}
return true;
});

function getFileExportPath(f: string) {
return path.relative(folderPath, path.dirname(f));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import chalk from 'chalk';
import { UDPATE_CONFIG } from '../constants.js';
import { getConfig } from '../utils/utils.config.js';
import { printBlueBox, printRedBox } from '../utils/utils.console.js';
import { getOnlyExistingInCwd, removeFilesInCwd } from '../utils/utils.files.js';
import { updateGoSdkAndModules } from '../utils/utils.goSdk.js';
Expand All @@ -23,6 +24,10 @@ export const standardUpdate = async () => {
await updateGoSdkAndModules(process.cwd());

const filesToRemove = getOnlyExistingInCwd(UDPATE_CONFIG.filesToRemove);

if (Boolean(getConfig().features.useExperimentalRspack)) {
filesToRemove.push('./config/webpack');
}
if (filesToRemove.length) {
removeFilesInCwd(filesToRemove);
}
Expand Down
1 change: 1 addition & 0 deletions packages/create-plugin/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export const DEFAULT_FEATURE_FLAGS = {
useReactRouterV6: true,
bundleGrafanaUI: false,
usePlaywright: true,
useExperimentalRspack: false,
};

export const GRAFANA_FE_PACKAGES = [
Expand Down
2 changes: 2 additions & 0 deletions packages/create-plugin/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,7 @@ export type TemplateData = {
reactRouterVersion: string;
usePlaywright: boolean;
useCypress: boolean;
useExperimentalRspack: boolean;
pluginExecutable?: string;
frontendBundler: 'webpack' | 'rspack';
};
1 change: 1 addition & 0 deletions packages/create-plugin/src/utils/utils.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export type FeatureFlags = {
// (Attention! We always scaffold new projects with React Router v6, so if you are changing this to `false` manually you will need to make changes to the React code as well.)
useReactRouterV6?: boolean;
usePlaywright?: boolean;
useExperimentalRspack?: boolean;
};

export type CreatePluginConfig = UserConfig & {
Expand Down
5 changes: 5 additions & 0 deletions packages/create-plugin/src/utils/utils.templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ export function getTemplateData(cliArgs?: GenerateCliArgs): TemplateData {
const getReactRouterVersion = (pluginType: string) => (shouldUseReactRouterV6(pluginType) ? '6.22.0' : '5.2.0');
const isAppType = (pluginType: string) => pluginType === PLUGIN_TYPES.app || pluginType === PLUGIN_TYPES.scenes;
const isNPM = (packageManagerName: string) => packageManagerName === 'npm';
const frontendBundler = features.useExperimentalRspack ? 'rspack' : 'webpack';

let templateData: TemplateData;

Expand All @@ -132,6 +133,8 @@ export function getTemplateData(cliArgs?: GenerateCliArgs): TemplateData {
reactRouterVersion: getReactRouterVersion(cliArgs.pluginType),
usePlaywright,
useCypress,
useExperimentalRspack: Boolean(features.useExperimentalRspack),
frontendBundler,
};
// Updating or migrating a plugin
// (plugin.json and package.json files are only present if it's an existing plugin)
Expand All @@ -158,6 +161,8 @@ export function getTemplateData(cliArgs?: GenerateCliArgs): TemplateData {
usePlaywright,
useCypress,
pluginExecutable: pluginJson.executable,
useExperimentalRspack: Boolean(features.useExperimentalRspack),
frontendBundler,
};
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import * as webpack from 'webpack';

const PLUGIN_NAME = 'BuildModeRspackPlugin';

export class BuildModeRspackPlugin {
apply(compiler: webpack.Compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.processAssets.tap(
{
name: PLUGIN_NAME,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
(assets) => {
const assetName = 'plugin.json';
const asset = assets[assetName];
if (!asset) {
return;
}

const { RawSource } = compiler.webpack.sources;
const pluginJsonContent = JSON.parse(asset.source().toString());
const pluginJsonWithBuildMode = JSON.stringify(
{
...pluginJsonContent,
buildMode: compilation.options.mode,
},
null,
4
);
const source = new RawSource(pluginJsonWithBuildMode);
compilation.updateAsset(assetName, source);
}
);
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const SOURCE_DIR = 'src';
export const DIST_DIR = 'dist';
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
const path = require('path');
const WebSocket = require('ws');
const http = require('http');

class RspackLiveReloadPlugin {
constructor(options = {}) {
this.options = Object.assign(
{
port: 35729,
delay: 0,
appendScriptTag: true,
protocol: 'http',
},
options
);
}

apply(compiler) {
const isRspack = compiler.rspack !== undefined;
if (!isRspack) {
throw new Error('This plugin is designed to work with Rspack 1');
}

compiler.hooks.afterEmit.tap('RspackLiveReloadPlugin', (compilation) => {
this._startServer();
this._notifyClient();
});

compiler.hooks.done.tap('RspackLiveReloadPlugin', (stats) => {
if (this.options.appendScriptTag) {
this._injectLiveReloadScript(stats.compilation);
}
});
}

_startServer() {
if (this.server) {
return;
}

const port = this.options.port;

this.httpServer = http.createServer((req, res) => {
if (req.url === '/livereload.js') {
res.writeHead(200, { 'Content-Type': 'application/javascript' });
res.end(this._getLiveReloadScript());
} else {
res.writeHead(404);
res.end('Not Found');
}
});

this.server = new WebSocket.Server({ server: this.httpServer });
this.httpServer.listen(port, () => {
console.log(`LiveReload server started on http://localhost:${port}`);
});
}

_notifyClient() {
if (!this.server) {
return;
}

this.server.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ action: 'reload' }));
}
});
}

_injectLiveReloadScript(compilation) {
compilation.hooks.processAssets.tap(
{
name: 'RspackLiveReloadPlugin',
stage: compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
},
(assets) => {
Object.keys(assets).forEach((filename) => {
if (path.extname(filename) === '.html') {
const assetSource = compilation.getAsset(filename).source;
const updatedSource = assetSource
.source()
.replace('</body>', `<script src="http://localhost:${this.options.port}/livereload.js"></script></body>`);
compilation.updateAsset(filename, {
source: () => updatedSource,
size: () => updatedSource.length,
});
}
});
}
);
}

_getLiveReloadScript() {
return `
(function() {
if (typeof WebSocket === 'undefined') return;
const ws = new WebSocket('${this.options.protocol}://localhost:${this.options.port}');
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
if (data.action === 'reload') {
window.location.reload();
}
};
})();
`;
}
}

module.exports = RspackLiveReloadPlugin;
Loading
Loading