Skip to content

Add support for using the vite dev server on remotes #551

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

Open
wants to merge 28 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
84223bf
feat(dev): add support for using the vite dev server on remotes
jlillywhite-mc Dec 13, 2023
15cf8f1
Make it so that when multiple dependencies are loaded, importShared i…
jlillywhite-mc Dec 13, 2023
f29597e
wip: resolve importShared is not defined error.
jlillywhite-mc Feb 15, 2024
757f924
wip: get shared imports working in dev.
jlillywhite-mc Feb 16, 2024
b3d639c
Add a prepublishOnly step
jlillywhite-mc Jun 28, 2024
84c3e41
wip: Replace the prepare script
jlillywhite-mc Jun 28, 2024
8017628
wip: try to make installation from github work
jlillywhite-mc Jun 28, 2024
5127edf
Add support for a non-root base directory
jlillywhite-mc Jul 26, 2024
277ba84
add base dir to the exposed file path
jlillywhite-mc Jul 31, 2024
0a4e82d
Wait for config to load before building remote file and exposing modu…
jlillywhite-mc Jul 31, 2024
759d09d
Use fsImportPath first and fall back to urlImportPath
jlillywhite-mc Aug 21, 2024
1c50305
Allow consumers to set importRetryCount and onImportFail for remotes
jlillywhite-mc Jan 13, 2025
8b4c1c1
Fix some configuration issues
jlillywhite-mc Jan 13, 2025
0ba072b
pass more information to onImportFail
jlillywhite-mc Jan 13, 2025
e827e24
Allow reinit of a remote based on the retry count
jlillywhite-mc Jan 13, 2025
05c9cab
Check reInit value when reloading libraries
jlillywhite-mc Jan 14, 2025
a5c8b1d
Make re-imports work by adding a url querystring.
jlillywhite-mc Jan 14, 2025
ad09cb4
Return the output of the factory
jlillywhite-mc Jan 14, 2025
11692cd
Add a backoff and the ability to set it.
jlillywhite-mc Jan 14, 2025
5aefefc
Fix typing
jlillywhite-mc Jan 14, 2025
34acd66
Clean up and fix merge issue.
jlillywhite-mc Jan 14, 2025
f027cb0
Fix another merge issue
jlillywhite-mc Jan 14, 2025
e550867
Revert unnecessary changes
jlillywhite-mc Jan 14, 2025
4289022
Address code review comments.
jlillywhite-mc Jan 15, 2025
1e44e47
Address more code review feedback
jlillywhite-mc Jan 15, 2025
277bd86
Merge pull request #6 from MasterControlIncPublic/ARCH-547
jlillywhite-mc Jan 15, 2025
a5aa79d
Resolve merge issue
jlillywhite-mc Jan 16, 2025
e69872f
More merge issues.
jlillywhite-mc Jan 16, 2025
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
19 changes: 17 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,20 @@
"workspaces": [
"packages/**"
],
"files": [
"packages/lib/dist/*",
"packages/types/*"
],
"main": "./packages/lib/dist/index.js",
"module": "./packages/lib/dist/index.mjs",
"types": "./packages/lib/types/index.d.ts",
"exports": {
".": {
"types": "./packages/lib/types/index.d.ts",
"import": "./packages/lib/dist/index.mjs",
"require": "./packages/lib/dist/index.js"
}
},
"engines": {
"node": "^14.18.0 || >=16.0.0",
"pnpm": ">=8.0.1"
Expand All @@ -12,7 +26,7 @@
"license": "MulanPSL-2.0",
"scripts": {
"preinstall": "npx only-allow pnpm",
"prepare": "husky install",
"prepare": "pnpm run build",
"postinstall": "npx playwright install",
"lint-staged": "lint-staged",
"format": "prettier -w packages/lib/**/*.ts",
Expand Down Expand Up @@ -52,5 +66,6 @@
"eslint --cache --fix",
"eslint"
]
}
},
"packageManager": "[email protected]+sha512.140036830124618d624a2187b50d04289d5a087f326c9edfc0ccd733d76c4f52c3a313d4fc148794a2a9d81553016004e6742e8cf850670268a7387fc220c903"
}
1 change: 1 addition & 0 deletions packages/examples/react-vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"build:remotes": "pnpm --parallel --filter \"./remote\" build",
"serve:remotes": "pnpm --parallel --filter \"./remote\" serve",
"dev:hosts": "pnpm --filter \"./host\" dev",
"dev:remotes": "pnpm --filter \"./remote\" dev",
"stop": "kill-port --port 5000,5001"
},
"devDependencies": {
Expand Down
1 change: 1 addition & 0 deletions packages/examples/vue3-advanced-demo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"build:remotes": "pnpm --parallel --filter \"./team-blue\" --filter \"./team-green\" build",
"serve:remotes": "pnpm --parallel --filter \"./team-blue\" --filter \"./team-green\" serve",
"dev:hosts": "pnpm --filter \"./team-red\" dev",
"dev:remotes": "pnpm --parallel --filter \"./team-blue\" --filter \"./team-green\" dev",
"stop": "kill-port --port 5000,5001,5002",
"clean": "pnpm run clean"
},
Expand Down
5 changes: 3 additions & 2 deletions packages/lib/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,14 @@
},
"homepage": "https://github.com/originjs/vite-plugin-federation#readme",
"scripts": {
"build": "vite build",
"build": "vite build && tsc",
"dev": "vite build --watch",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s --commit-path ."
},
"dependencies": {
"estree-walker": "^3.0.2",
"magic-string": "^0.27.0"
"magic-string": "^0.27.0",
"rollup": "^3.9.1"
},
"devDependencies": {
"@rollup/plugin-virtual": "^3.0.1",
Expand Down
80 changes: 77 additions & 3 deletions packages/lib/src/dev/expose-development.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,91 @@
// SPDX-License-Identifier: MulanPSL-2.0
// *****************************************************************************

import { parseExposeOptions } from '../utils'
import { parsedOptions } from '../public'
import { resolve } from 'path'
import { getModuleMarker, normalizePath, parseExposeOptions } from '../utils'
import { EXTERNALS, SHARED, builderInfo, parsedOptions } from '../public'
import type { VitePluginFederationOptions } from 'types'
import type { PluginHooks } from '../../types/pluginHooks'
import { UserConfig, ViteDevServer } from 'vite'
import { importShared } from './import-shared'

export function devExposePlugin(
options: VitePluginFederationOptions
): PluginHooks {
parsedOptions.devExpose = parseExposeOptions(options)
let moduleMap = ''
let remoteFile: string | null = null

const exposeModules = (baseDir) => {
for (const item of parsedOptions.devExpose) {
const moduleName = getModuleMarker(`\${${item[0]}}`, SHARED)
EXTERNALS.push(moduleName)
const importPath = normalizePath(item[1].import)
const exposeFilepath = normalizePath(resolve(item[1].import))
moduleMap += `\n"${item[0]}":() => {
return __federation_import('/${importPath}', '${baseDir}@fs/${exposeFilepath}').then(module =>Object.keys(module).every(item => exportSet.has(item)) ? () => module.default : () => module)},`
}
}

const buildRemoteFile = (baseDir:string) => {
return `(${importShared})();
import RefreshRuntime from "${baseDir}@react-refresh"
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
const exportSet = new Set(['Module', '__esModule', 'default', '_export_sfc']);
let moduleMap = {
${moduleMap}
};
const __federation_import = async (urlImportPath, fsImportPath) => {
let importedModule;
try {
return await import(fsImportPath);
} catch(ex) {
return await import(urlImportPath);
}
};
export const get =(module) => {
if(!moduleMap[module]) throw new Error('Can not find remote module ' + module)
return moduleMap[module]();
};
export const init =(shareScope) => {
globalThis.__federation_shared__= globalThis.__federation_shared__|| {};
Object.entries(shareScope).forEach(([key, value]) => {
const versionKey = Object.keys(value)[0];
const versionValue = Object.values(value)[0];
const scope = versionValue.scope || 'default'
globalThis.__federation_shared__[scope] = globalThis.__federation_shared__[scope] || {};
const shared= globalThis.__federation_shared__[scope];
(shared[key] = shared[key]||{})[versionKey] = versionValue;
});
}
`
}

return {
name: 'originjs:expose-development'
name: 'originjs:expose-development',
config: (config: UserConfig) => {
if (config.base) {
exposeModules(config.base)
remoteFile = buildRemoteFile(config.base)
}
},
configureServer: (server: ViteDevServer) => {
const remoteFilePath = `${builderInfo.assetsDir}/${options.filename}`
server.middlewares.use((req, res, next) => {
if (req.url && req.url.includes(remoteFilePath)) {
res.writeHead(200, 'OK', {
'Content-Type': 'text/javascript',
'Access-Control-Allow-Origin': '*'
})
res.write(remoteFile)
res.end()
} else {
next()
}
})
}
}
}
40 changes: 40 additions & 0 deletions packages/lib/src/dev/import-shared.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
export const importShared = function () {
if (!globalThis.importShared) {
const moduleCache = Object.create(null)
const getSharedFromRuntime = async (name, shareScope) => {
let module = null
if (globalThis?.__federation_shared__?.[shareScope]?.[name]) {
const versionObj = globalThis.__federation_shared__[shareScope][name]
const versionValue = Object.values(versionObj)[0]
module = await (await versionValue.get())()
}
if (module) {
return flattenModule(module, name)
}
}
const flattenModule = (module, name) => {
// use a shared module which export default a function will getting error 'TypeError: xxx is not a function'
if (typeof module.default === 'function') {
Object.keys(module).forEach((key) => {
if (key !== 'default') {
module.default[key] = module[key]
}
})
moduleCache[name] = module.default
return module.default
}
if (module.default) module = Object.assign({}, module.default, module)
moduleCache[name] = module
return module
}
globalThis.importShared = async (name, shareScope = 'default') => {
try {
return moduleCache[name]
? new Promise((r) => r(moduleCache[name]))
: (await getSharedFromRuntime(name, shareScope)) || null
} catch (ex) {
console.log(ex)
}
}
}
}
Loading
Loading