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

fix: HMR #2316

Draft
wants to merge 17 commits into
base: main
Choose a base branch
from
Draft
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
65 changes: 28 additions & 37 deletions packages/router-plugin/src/core/code-splitter/compilers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import _generate from '@babel/generator'
import * as template from '@babel/template'
import { deadCodeElimination } from 'babel-dead-code-elimination'

import { splitPrefix } from '../constants'
import { splitToken } from '../constants'
import { parseAst } from './ast'
import type { ParseAstOptions } from './ast'

Expand Down Expand Up @@ -49,7 +49,7 @@ export function compileCodeSplitReferenceRoute(opts: ParseAstOptions) {
enter(programPath, programState) {
const state = programState as unknown as State

const splitUrl = `${splitPrefix}:${opts.filename}?${splitPrefix}`
const splitUrl = `${opts.filename}?${splitToken}`

/**
* If the component for the route is being imported from
Expand Down Expand Up @@ -85,8 +85,6 @@ export function compileCodeSplitReferenceRoute(opts: ParseAstOptions) {
path.parentPath.node.arguments[0],
)

let found = false

const hasImportedOrDefinedIdentifier = (name: string) => {
return programPath.scope.hasBinding(name)
}
Expand Down Expand Up @@ -150,14 +148,6 @@ export function compileCodeSplitReferenceRoute(opts: ParseAstOptions) {
prop.value = template.expression(
`lazyRouteComponent($$splitComponentImporter, 'component')`,
)()

programPath.pushContainer('body', [
template.statement(
`function DummyComponent() { return null }`,
)(),
])

found = true
}
} else if (prop.key.name === 'loader') {
const value = prop.value
Expand Down Expand Up @@ -207,8 +197,6 @@ export function compileCodeSplitReferenceRoute(opts: ParseAstOptions) {
prop.value = template.expression(
`lazyFn($$splitLoaderImporter, 'loader')`,
)()

found = true
}
}
}
Expand All @@ -218,11 +206,13 @@ export function compileCodeSplitReferenceRoute(opts: ParseAstOptions) {
})
}

if (found as boolean) {
programPath.pushContainer('body', [
template.statement(`function TSR_Dummy_Component() {}`)(),
])
}
// if (found as boolean) {
// }
programPath.pushContainer('body', [
template.statement(
`export function TSR_Dummy_Component() { return null }`,
)(),
])
}
},
},
Expand Down Expand Up @@ -362,23 +352,24 @@ export function compileCodeSplitVirtualRoute(opts: ParseAstOptions) {
splitNode = binding?.path.node
}

let componentId =
splitType === 'component' ? 'SplitComponent' : 'SplitLoader'

// Add the node to the program
if (splitNode) {
if (t.isFunctionDeclaration(splitNode)) {
componentId = splitNode.id?.name || 'SplitComponent'
programPath.pushContainer(
'body',
t.variableDeclaration('const', [
t.variableDeclarator(
t.identifier(splitType),
t.functionExpression(
splitNode.id || null, // Anonymize the function expression
splitNode.params,
splitNode.body,
splitNode.generator,
splitNode.async,
),
),
]),
// Push the function declaration to the program
// but change the name to the componentId
t.functionDeclaration(
t.identifier(componentId),
splitNode.params,
splitNode.body,
splitNode.generator,
splitNode.async,
),
)
} else if (
t.isFunctionExpression(splitNode) ||
Expand All @@ -388,7 +379,7 @@ export function compileCodeSplitVirtualRoute(opts: ParseAstOptions) {
'body',
t.variableDeclaration('const', [
t.variableDeclarator(
t.identifier(splitType),
t.identifier(componentId),
splitNode as any,
),
]),
Expand All @@ -401,7 +392,7 @@ export function compileCodeSplitVirtualRoute(opts: ParseAstOptions) {
'body',
t.variableDeclaration('const', [
t.variableDeclarator(
t.identifier(splitType),
t.identifier(componentId),
splitNode.local,
),
]),
Expand Down Expand Up @@ -429,7 +420,7 @@ export function compileCodeSplitVirtualRoute(opts: ParseAstOptions) {
programPath.pushContainer(
'body',
t.variableDeclaration('const', [
t.variableDeclarator(t.identifier(splitType), expression),
t.variableDeclarator(t.identifier(componentId), expression),
]),
)
} else {
Expand All @@ -453,7 +444,7 @@ export function compileCodeSplitVirtualRoute(opts: ParseAstOptions) {
programPath.pushContainer('body', [
t.exportNamedDeclaration(null, [
t.exportSpecifier(
t.identifier(splitType),
t.identifier(componentId),
t.identifier(splitType),
),
]),
Expand All @@ -478,7 +469,7 @@ export function compileCodeSplitVirtualRoute(opts: ParseAstOptions) {
),
),
t.stringLiteral(
opts.filename.split(`?${splitPrefix}`)[0] as string,
opts.filename.split(`?${splitToken}`)[0] as string,
),
),
)
Expand All @@ -502,7 +493,7 @@ export function compileCodeSplitVirtualRoute(opts: ParseAstOptions) {
return str
}, '')

const warningMessage = `These exports from "${opts.filename.replace('?' + splitPrefix, '')}" are not being code-split and will increase your bundle size: ${list}\nThese should either have their export statements removed or be imported from another file that is not a route.`
const warningMessage = `These exports from "${opts.filename.replace('?' + splitToken, '')}" are not being code-split and will increase your bundle size: ${list}\nThese should either have their export statements removed or be imported from another file that is not a route.`
console.warn(warningMessage)

// append this warning to the file using a template
Expand Down
2 changes: 1 addition & 1 deletion packages/router-plugin/src/core/constants.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export const CONFIG_FILE_NAME = 'tsr.config.json'
export const splitPrefix = 'tsr-split'
export const splitToken = 'tsr-split'
78 changes: 9 additions & 69 deletions packages/router-plugin/src/core/router-code-splitter-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
compileCodeSplitReferenceRoute,
compileCodeSplitVirtualRoute,
} from './code-splitter/compilers'
import { splitPrefix } from './constants'
import { splitToken } from './constants'

import type { Config } from './config'
import type { UnpluginContextMeta, UnpluginFactory } from 'unplugin'
Expand Down Expand Up @@ -56,9 +56,6 @@ plugins: [
}
}

const PLUGIN_NAME = 'unplugin:router-code-splitter'
const JoinedSplitPrefix = splitPrefix + ':'

export const unpluginRouterCodeSplitterFactory: UnpluginFactory<
Partial<Config> | undefined
> = (options = {}, { framework }) => {
Expand Down Expand Up @@ -110,18 +107,6 @@ export const unpluginRouterCodeSplitterFactory: UnpluginFactory<
return {
name: 'router-code-splitter-plugin',
enforce: 'pre',

resolveId(source) {
if (!userConfig.autoCodeSplitting) {
return null
}

if (source.startsWith(splitPrefix + ':')) {
return source.replace(splitPrefix + ':', '')
}
return null
},

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Look ma'! No resolveId!

transform(code, id) {
if (!userConfig.autoCodeSplitting) {
return null
Expand All @@ -131,7 +116,7 @@ export const unpluginRouterCodeSplitterFactory: UnpluginFactory<
url.searchParams.delete('v')
id = fileURLToPath(url).replace(/\\/g, '/')

if (id.includes(splitPrefix)) {
if (id.includes(splitToken)) {
return handleSplittingFile(code, id)
} else if (
fileIsInRoutesDirectory(id, userConfig.routesDirectory) &&
Expand All @@ -158,15 +143,9 @@ export const unpluginRouterCodeSplitterFactory: UnpluginFactory<
return undefined
}

let id = transformId

if (id.startsWith(JoinedSplitPrefix)) {
id = id.replace(JoinedSplitPrefix, '')
}

if (
fileIsInRoutesDirectory(id, userConfig.routesDirectory) ||
id.includes(splitPrefix)
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I honestly don't know if this was still necessary or not....

fileIsInRoutesDirectory(transformId, userConfig.routesDirectory) ||
transformId.includes(splitToken)
) {
return true
}
Expand All @@ -179,58 +158,19 @@ export const unpluginRouterCodeSplitterFactory: UnpluginFactory<

userConfig = getConfig(options, ROOT)
},
// handleHotUpdate({ file, server, modules }) {
// return []
// },
},

rspack(compiler) {
rspack() {
ROOT = process.cwd()

compiler.hooks.beforeCompile.tap(PLUGIN_NAME, (self) => {
self.normalModuleFactory.hooks.beforeResolve.tap(
PLUGIN_NAME,
(resolveData: { request: string }) => {
if (resolveData.request.includes(JoinedSplitPrefix)) {
resolveData.request = resolveData.request.replace(
JoinedSplitPrefix,
'',
)
}
},
)
})

userConfig = getConfig(options, ROOT)
schiller-manuel marked this conversation as resolved.
Show resolved Hide resolved
},

webpack(compiler) {
webpack() {
ROOT = process.cwd()

compiler.hooks.beforeCompile.tap(PLUGIN_NAME, (self) => {
self.normalModuleFactory.hooks.beforeResolve.tap(
PLUGIN_NAME,
(resolveData: { request: string }) => {
if (resolveData.request.includes(JoinedSplitPrefix)) {
resolveData.request = resolveData.request.replace(
JoinedSplitPrefix,
'',
)
}
},
)
})

userConfig = getConfig(options, ROOT)

if (
userConfig.autoCodeSplitting &&
compiler.options.mode === 'production'
) {
compiler.hooks.done.tap(PLUGIN_NAME, () => {
console.info('✅ ' + PLUGIN_NAME + ': code-splitting done!')
setTimeout(() => {
process.exit(0)
})
})
}
},
}
}
8 changes: 4 additions & 4 deletions packages/router-plugin/tests/code-splitter.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { readFile, readdir } from 'fs/promises'
import path from 'path'
import { readFile, readdir } from 'node:fs/promises'
import path from 'node:path'
import { describe, expect, it } from 'vitest'

import {
compileCodeSplitReferenceRoute,
compileCodeSplitVirtualRoute,
} from '../src/core/code-splitter/compilers'
import { splitPrefix } from '../src/core/constants'
import { splitToken } from '../src/core/constants'

async function getFilenames() {
return await readdir(path.resolve(__dirname, './code-splitter/test-files'))
Expand Down Expand Up @@ -46,7 +46,7 @@ describe('code-splitter works', async () => {
const splitResult = compileCodeSplitVirtualRoute({
code: code,
root: './code-splitter/test-files',
filename: `${filename}?${splitPrefix}`,
filename: `${filename}?${splitToken}`,
})

await expect(splitResult.code).toMatchFileSnapshot(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
const $$splitLoaderImporter = () => import('tsr-split:destructured-react-memo-imported-component.tsx?tsr-split');
const $$splitLoaderImporter = () => import('destructured-react-memo-imported-component.tsx?tsr-split');
import { lazyFn } from '@tanstack/react-router';
const $$splitComponentImporter = () => import('tsr-split:destructured-react-memo-imported-component.tsx?tsr-split');
const $$splitComponentImporter = () => import('destructured-react-memo-imported-component.tsx?tsr-split');
import { lazyRouteComponent } from '@tanstack/react-router';
import { createFileRoute } from '@tanstack/react-router';
export const Route = createFileRoute('/')({
component: lazyRouteComponent($$splitComponentImporter, 'component'),
loader: lazyFn($$splitLoaderImporter, 'loader')
});
});
export function TSR_Dummy_Component() {
return null;
}
8 changes: 4 additions & 4 deletions ...plugin/tests/code-splitter/snapshots/[email protected]
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { importedLoader } from '../shared/imported';
function Component() {
return <div>Component</div>;
}
const component = memo(Component);
export { component };
const loader = importedLoader;
export { loader };
const SplitComponent = memo(Component);
export { SplitComponent as component };
const SplitLoader = importedLoader;
export { SplitLoader as loader };
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
const $$splitComponentImporter = () => import('tsr-split:function-declaration.tsx?tsr-split');
const $$splitComponentImporter = () => import('function-declaration.tsx?tsr-split');
import { lazyRouteComponent } from '@tanstack/react-router';
const $$splitLoaderImporter = () => import('tsr-split:function-declaration.tsx?tsr-split');
const $$splitLoaderImporter = () => import('function-declaration.tsx?tsr-split');
import { lazyFn } from '@tanstack/react-router';
import { createFileRoute } from '@tanstack/react-router';
export const Route = createFileRoute('/posts')({
loader: lazyFn($$splitLoaderImporter, 'loader'),
component: lazyRouteComponent($$splitComponentImporter, 'component')
});
});
export function TSR_Dummy_Component() {
return null;
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Link, Outlet } from '@tanstack/react-router';
import { fetchPosts } from '../posts';
import { Route } from "function-declaration.tsx";
const component = function PostsComponent() {
function PostsComponent() {
const posts = Route.useLoaderData();
return <div className="p-2 flex gap-2">
<ul className="list-disc pl-4">
Expand All @@ -23,7 +23,7 @@ const component = function PostsComponent() {
<hr />
<Outlet />
</div>;
};
export { component };
const loader = fetchPosts;
export { loader };
}
export { PostsComponent as component };
const SplitLoader = fetchPosts;
export { SplitLoader as loader };
Loading