@tanstack/router-plugin 1.95.6 → 1.96.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"compilers.js","sources":["../../../../src/core/code-splitter/compilers.ts"],"sourcesContent":["import * as t from '@babel/types'\nimport babel from '@babel/core'\nimport _generate from '@babel/generator'\nimport * as template from '@babel/template'\nimport { deadCodeElimination } from 'babel-dead-code-elimination'\n\nimport { splitPrefix } from '../constants'\nimport { parseAst } from './ast'\nimport type { ParseAstOptions } from './ast'\n\nconst debug = process.env.TSR_VITE_DEBUG\n\n// Babel is a CJS package and uses `default` as named binding (`exports.default =`).\n// https://github.com/babel/babel/issues/15269.\nlet generate = (_generate as any)['default'] as typeof _generate\n\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nif (!generate) {\n generate = _generate\n}\n\ntype SplitModulesById = Record<\n string,\n { id: string; node: t.FunctionExpression }\n>\n\ninterface State {\n filename: string\n opts: {\n minify: boolean\n root: string\n }\n imported: Record<string, boolean>\n refs: Set<any>\n serverIndex: number\n splitIndex: number\n splitModulesById: SplitModulesById\n}\n\nexport function compileCodeSplitReferenceRoute(opts: ParseAstOptions) {\n const ast = parseAst(opts)\n\n babel.traverse(ast, {\n Program: {\n enter(programPath, programState) {\n const state = programState as unknown as State\n\n const splitUrl = `${splitPrefix}:${opts.filename}?${splitPrefix}`\n\n /**\n * If the component for the route is being imported from\n * another file, this is to track the path to that file\n * the path itself doesn't matter, we just need to keep\n * track of it so that we can remove it from the imports\n * list if it's not being used like:\n *\n * `import '../shared/imported'`\n */\n let existingCompImportPath: string | null = null\n let existingLoaderImportPath: string | null = null\n\n programPath.traverse(\n {\n CallExpression: (path) => {\n if (!t.isIdentifier(path.node.callee)) {\n return\n }\n\n if (\n !(\n path.node.callee.name === 'createRoute' ||\n path.node.callee.name === 'createFileRoute'\n )\n ) {\n return\n }\n\n if (t.isCallExpression(path.parentPath.node)) {\n const options = resolveIdentifier(\n path,\n path.parentPath.node.arguments[0],\n )\n\n let found = false\n\n const hasImportedOrDefinedIdentifier = (name: string) => {\n return programPath.scope.hasBinding(name)\n }\n\n if (t.isObjectExpression(options)) {\n options.properties.forEach((prop) => {\n if (t.isObjectProperty(prop)) {\n if (t.isIdentifier(prop.key)) {\n if (prop.key.name === 'component') {\n const value = prop.value\n\n let shouldSplit = true\n\n if (t.isIdentifier(value)) {\n existingCompImportPath =\n getImportSpecifierAndPathFromLocalName(\n programPath,\n value.name,\n ).path\n\n // exported identifiers should not be split\n // since they are already being imported\n // and need to be retained in the compiled file\n const isExported = hasExport(ast, value)\n shouldSplit = !isExported\n\n if (shouldSplit) {\n removeIdentifierLiteral(path, value)\n }\n }\n\n if (shouldSplit) {\n // Prepend the import statement to the program along with the importer function\n // Check to see if lazyRouteComponent is already imported before attempting\n // to import it again\n\n if (\n !hasImportedOrDefinedIdentifier(\n 'lazyRouteComponent',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.statement(\n `import { lazyRouteComponent } from '@tanstack/react-router'`,\n )(),\n ])\n }\n\n if (\n !hasImportedOrDefinedIdentifier(\n '$$splitComponentImporter',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.statement(\n `const $$splitComponentImporter = () => import('${splitUrl}')`,\n )(),\n ])\n }\n\n prop.value = template.expression(\n `lazyRouteComponent($$splitComponentImporter, 'component', () => Route.ssr)`,\n )()\n\n programPath.pushContainer('body', [\n template.statement(\n `function DummyComponent() { return null }`,\n )(),\n ])\n\n found = true\n }\n } else if (prop.key.name === 'loader') {\n const value = prop.value\n\n let shouldSplit = true\n\n if (t.isIdentifier(value)) {\n existingLoaderImportPath =\n getImportSpecifierAndPathFromLocalName(\n programPath,\n value.name,\n ).path\n\n // exported identifiers should not be split\n // since they are already being imported\n // and need to be retained in the compiled file\n const isExported = hasExport(ast, value)\n shouldSplit = !isExported\n\n if (shouldSplit) {\n removeIdentifierLiteral(path, value)\n }\n }\n\n if (shouldSplit) {\n // Prepend the import statement to the program along with the importer function\n if (!hasImportedOrDefinedIdentifier('lazyFn')) {\n programPath.unshiftContainer('body', [\n template.smart(\n `import { lazyFn } from '@tanstack/react-router'`,\n )() as t.Statement,\n ])\n }\n\n if (\n !hasImportedOrDefinedIdentifier(\n '$$splitLoaderImporter',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.statement(\n `const $$splitLoaderImporter = () => import('${splitUrl}')`,\n )(),\n ])\n }\n\n prop.value = template.expression(\n `lazyFn($$splitLoaderImporter, 'loader')`,\n )()\n\n found = true\n }\n }\n }\n }\n\n programPath.scope.crawl()\n })\n }\n\n if (found as boolean) {\n programPath.pushContainer('body', [\n template.statement(`function TSR_Dummy_Component() {}`)(),\n ])\n }\n }\n },\n },\n state,\n )\n\n /**\n * If the component for the route is being imported,\n * and it's not being used, remove the import statement\n * from the program, by checking that the import has no\n * specifiers\n */\n if (\n (existingCompImportPath as string | null) ||\n (existingLoaderImportPath as string | null)\n ) {\n programPath.traverse({\n ImportDeclaration(path) {\n if (path.node.specifiers.length > 0) return\n if (\n path.node.source.value === existingCompImportPath ||\n path.node.source.value === existingLoaderImportPath\n ) {\n path.remove()\n }\n },\n })\n }\n },\n },\n })\n\n if (debug) console.info('')\n if (debug) console.info('Dead Code Elimination Input 1:')\n if (debug) console.info(generate(ast, { sourceMaps: true }).code)\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n\n deadCodeElimination(ast)\n\n if (debug) console.info('')\n if (debug) console.info('Dead Code Elimination Output 1:')\n if (debug) console.info(generate(ast, { sourceMaps: true }).code)\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n\n return generate(ast, {\n sourceMaps: true,\n sourceFileName: opts.filename,\n })\n}\n\nconst splitNodeTypes = ['component', 'loader'] as const\ntype SplitNodeType = (typeof splitNodeTypes)[number]\n\nexport function compileCodeSplitVirtualRoute(opts: ParseAstOptions) {\n const ast = parseAst(opts)\n\n const knownExportedIdents = new Set<string>()\n\n babel.traverse(ast, {\n Program: {\n enter(programPath, programState) {\n const state = programState as unknown as State\n\n const splitNodesByType: Record<SplitNodeType, t.Node | undefined> = {\n component: undefined,\n loader: undefined,\n }\n\n // Find the node\n programPath.traverse(\n {\n CallExpression: (path) => {\n if (!t.isIdentifier(path.node.callee)) {\n return\n }\n\n if (\n !(\n path.node.callee.name === 'createRoute' ||\n path.node.callee.name === 'createFileRoute'\n )\n ) {\n return\n }\n\n if (t.isCallExpression(path.parentPath.node)) {\n const options = resolveIdentifier(\n path,\n path.parentPath.node.arguments[0],\n )\n\n if (t.isObjectExpression(options)) {\n options.properties.forEach((prop) => {\n if (t.isObjectProperty(prop)) {\n splitNodeTypes.forEach((splitType) => {\n if (\n !t.isIdentifier(prop.key) ||\n prop.key.name !== splitType\n ) {\n return\n }\n\n const value = prop.value\n\n let isExported = false\n if (t.isIdentifier(value)) {\n isExported = hasExport(ast, value)\n if (isExported) {\n knownExportedIdents.add(value.name)\n }\n }\n\n // If the node is exported, we need to remove\n // the export from the split file\n if (isExported && t.isIdentifier(value)) {\n removeExports(ast, value)\n } else {\n splitNodesByType[splitType] = prop.value\n }\n })\n }\n })\n\n // Remove all of the options\n options.properties = []\n }\n }\n },\n },\n state,\n )\n\n splitNodeTypes.forEach((splitType) => {\n let splitNode = splitNodesByType[splitType]\n\n if (!splitNode) {\n return\n }\n\n while (t.isIdentifier(splitNode)) {\n const binding = programPath.scope.getBinding(splitNode.name)\n splitNode = binding?.path.node\n }\n\n // Add the node to the program\n if (splitNode) {\n if (t.isFunctionDeclaration(splitNode)) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(splitType),\n t.functionExpression(\n splitNode.id || null, // Anonymize the function expression\n splitNode.params,\n splitNode.body,\n splitNode.generator,\n splitNode.async,\n ),\n ),\n ]),\n )\n } else if (\n t.isFunctionExpression(splitNode) ||\n t.isArrowFunctionExpression(splitNode)\n ) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(splitType),\n splitNode as any,\n ),\n ]),\n )\n } else if (\n t.isImportSpecifier(splitNode) ||\n t.isImportDefaultSpecifier(splitNode)\n ) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(splitType),\n splitNode.local,\n ),\n ]),\n )\n } else if (t.isVariableDeclarator(splitNode)) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(t.identifier(splitType), splitNode.init),\n ]),\n )\n } else if (t.isCallExpression(splitNode)) {\n const outputSplitNodeCode = generate(splitNode).code\n const splitNodeAst = babel.parse(outputSplitNodeCode)\n\n if (!splitNodeAst) {\n throw new Error(\n `Failed to parse the generated code for \"${splitType}\" in the node type \"${splitNode.type}\"`,\n )\n }\n\n const statement = splitNodeAst.program.body[0]\n\n if (!statement) {\n throw new Error(\n `Failed to parse the generated code for \"${splitType}\" in the node type \"${splitNode.type}\" as no statement was found in the program body`,\n )\n }\n\n if (t.isExpressionStatement(statement)) {\n const expression = statement.expression\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(t.identifier(splitType), expression),\n ]),\n )\n } else {\n throw new Error(\n `Unexpected expression type encounter for \"${splitType}\" in the node type \"${splitNode.type}\"`,\n )\n }\n } else {\n console.info('Unexpected splitNode type:', splitNode)\n throw new Error(`Unexpected splitNode type ☝️: ${splitNode.type}`)\n }\n }\n\n // If the splitNode exists at the top of the program\n // then we need to remove that copy\n programPath.node.body = programPath.node.body.filter((node) => {\n return node !== splitNode\n })\n\n // Export the node\n programPath.pushContainer('body', [\n t.exportNamedDeclaration(null, [\n t.exportSpecifier(\n t.identifier(splitType),\n t.identifier(splitType),\n ),\n ]),\n ])\n })\n\n // convert exports to imports from the original file\n programPath.traverse({\n ExportNamedDeclaration(path) {\n // e.g. export const x = 1 or export { x }\n // becomes\n // import { x } from '${opts.id}'\n\n if (path.node.declaration) {\n if (t.isVariableDeclaration(path.node.declaration)) {\n path.replaceWith(\n t.importDeclaration(\n path.node.declaration.declarations.map((decl) =>\n t.importSpecifier(\n t.identifier((decl.id as any).name),\n t.identifier((decl.id as any).name),\n ),\n ),\n t.stringLiteral(\n opts.filename.split(`?${splitPrefix}`)[0] as string,\n ),\n ),\n )\n }\n }\n },\n })\n },\n },\n })\n\n if (debug) console.info('')\n if (debug) console.info('Dead Code Elimination Input 2:')\n if (debug) console.info(generate(ast, { sourceMaps: true }).code)\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n\n deadCodeElimination(ast)\n\n if (debug) console.info('')\n if (debug) console.info('Dead Code Elimination Output 2:')\n if (debug) console.info(generate(ast, { sourceMaps: true }).code)\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n\n // if there are exported identifiers, then we need to add a warning\n // to the file to let the user know that the exported identifiers\n // will not in the split file but in the original file, therefore\n // increasing the bundle size\n if (knownExportedIdents.size > 0) {\n const list = Array.from(knownExportedIdents).reduce((str, ident) => {\n str += `\\n- ${ident}`\n return str\n }, '')\n\n 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.`\n console.warn(warningMessage)\n\n // append this warning to the file using a template\n if (process.env.NODE_ENV !== 'production') {\n const warningTemplate = template.statement(\n `console.warn(${JSON.stringify(warningMessage)})`,\n )()\n ast.program.body.unshift(warningTemplate)\n }\n }\n\n return generate(ast, {\n sourceMaps: true,\n sourceFileName: opts.filename,\n })\n}\n\nfunction getImportSpecifierAndPathFromLocalName(\n programPath: babel.NodePath<t.Program>,\n name: string,\n): {\n specifier:\n | t.ImportSpecifier\n | t.ImportDefaultSpecifier\n | t.ImportNamespaceSpecifier\n | null\n path: string | null\n} {\n let specifier:\n | t.ImportSpecifier\n | t.ImportDefaultSpecifier\n | t.ImportNamespaceSpecifier\n | null = null\n let path: string | null = null\n\n programPath.traverse({\n ImportDeclaration(importPath) {\n const found = importPath.node.specifiers.find(\n (targetSpecifier) => targetSpecifier.local.name === name,\n )\n if (found) {\n specifier = found\n path = importPath.node.source.value\n }\n },\n })\n\n return { specifier, path }\n}\n\n// Reusable function to get literal value or resolve variable to literal\nfunction resolveIdentifier(path: any, node: any) {\n if (t.isIdentifier(node)) {\n const binding = path.scope.getBinding(node.name)\n if (\n binding\n // && binding.kind === 'const'\n ) {\n const declarator = binding.path.node\n if (t.isObjectExpression(declarator.init)) {\n return declarator.init\n } else if (t.isFunctionDeclaration(declarator.init)) {\n return declarator.init\n }\n }\n return undefined\n }\n\n return node\n}\n\nfunction removeIdentifierLiteral(path: any, node: any) {\n if (t.isIdentifier(node)) {\n const binding = path.scope.getBinding(node.name)\n if (binding) {\n binding.path.remove()\n }\n }\n}\n\nfunction hasExport(ast: t.File, node: t.Identifier): boolean {\n let found = false\n\n babel.traverse(ast, {\n ExportNamedDeclaration(path) {\n if (path.node.declaration) {\n // declared as `const loaderFn = () => {}`\n if (t.isVariableDeclaration(path.node.declaration)) {\n path.node.declaration.declarations.forEach((decl) => {\n if (t.isVariableDeclarator(decl)) {\n if (t.isIdentifier(decl.id)) {\n if (decl.id.name === node.name) {\n found = true\n }\n }\n }\n })\n }\n\n // declared as `function loaderFn() {}`\n if (t.isFunctionDeclaration(path.node.declaration)) {\n if (t.isIdentifier(path.node.declaration.id)) {\n if (path.node.declaration.id.name === node.name) {\n found = true\n }\n }\n }\n }\n },\n ExportDefaultDeclaration(path) {\n if (t.isIdentifier(path.node.declaration)) {\n if (path.node.declaration.name === node.name) {\n found = true\n }\n }\n },\n })\n\n return found\n}\n\nfunction removeExports(ast: t.File, node: t.Identifier): boolean {\n let removed = false\n\n babel.traverse(ast, {\n ExportNamedDeclaration(path) {\n if (path.node.declaration) {\n // declared as `const loaderFn = () => {}`\n if (t.isVariableDeclaration(path.node.declaration)) {\n path.node.declaration.declarations.forEach((decl) => {\n if (t.isVariableDeclarator(decl)) {\n if (t.isIdentifier(decl.id)) {\n if (decl.id.name === node.name) {\n path.remove()\n removed = true\n }\n }\n }\n })\n } else if (t.isFunctionDeclaration(path.node.declaration)) {\n if (t.isIdentifier(path.node.declaration.id)) {\n if (path.node.declaration.id.name === node.name) {\n path.remove()\n removed = true\n }\n }\n }\n }\n },\n ExportDefaultDeclaration(path) {\n if (t.isIdentifier(path.node.declaration)) {\n if (path.node.declaration.name === node.name) {\n path.remove()\n removed = true\n }\n }\n },\n })\n\n return removed\n}\n"],"names":[],"mappings":";;;;;;;AAUA,MAAM,QAAQ,QAAQ,IAAI;AAI1B,IAAI,WAAY,UAAkB,SAAS;AAG3C,IAAI,CAAC,UAAU;AACF,aAAA;AACb;AAoBO,SAAS,+BAA+B,MAAuB;AAC9D,QAAA,MAAM,SAAS,IAAI;AAEzB,QAAM,SAAS,KAAK;AAAA,IAClB,SAAS;AAAA,MACP,MAAM,aAAa,cAAc;AAC/B,cAAM,QAAQ;AAEd,cAAM,WAAW,GAAG,WAAW,IAAI,KAAK,QAAQ,IAAI,WAAW;AAW/D,YAAI,yBAAwC;AAC5C,YAAI,2BAA0C;AAElC,oBAAA;AAAA,UACV;AAAA,YACE,gBAAgB,CAAC,SAAS;AACxB,kBAAI,CAAC,EAAE,aAAa,KAAK,KAAK,MAAM,GAAG;AACrC;AAAA,cAAA;AAIA,kBAAA,EACE,KAAK,KAAK,OAAO,SAAS,iBAC1B,KAAK,KAAK,OAAO,SAAS,oBAE5B;AACA;AAAA,cAAA;AAGF,kBAAI,EAAE,iBAAiB,KAAK,WAAW,IAAI,GAAG;AAC5C,sBAAM,UAAU;AAAA,kBACd;AAAA,kBACA,KAAK,WAAW,KAAK,UAAU,CAAC;AAAA,gBAClC;AAEA,oBAAI,QAAQ;AAEN,sBAAA,iCAAiC,CAAC,SAAiB;AAChD,yBAAA,YAAY,MAAM,WAAW,IAAI;AAAA,gBAC1C;AAEI,oBAAA,EAAE,mBAAmB,OAAO,GAAG;AACzB,0BAAA,WAAW,QAAQ,CAAC,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AEJ;AAAA,IACA,yBAAyB,MAAM;AAC7B,UAAI,EAAE,aAAa,KAAK,KAAK,WAAW,GAAG;AACzC,YAAI,KAAK,KAAK,YAAY,SAAS,KAAK,MAAM;AACpC,kBAAA;AAAA,QAAA;AAAA,MACV;AAAA,IACF;AAAA,EACF,CACD;AAEM,SAAA;AACT;AAEA,SAAS,cAAc,KAAa,MAA6B;AAC/D,MAAI,UAAU;AAEd,QAAM,SAAS,KAAK;AAAA,IAClB,uBAAuB,MAAM;AACvB,UAAA,KAAK,KAAK,aAAa;AAEzB,YAAI,EAAE,sBAAsB,KAAK,KAAK,WAAW,GAAG;AAClD,eAAK,KAAK,YAAY,aAAa,QAAQ,CAAC,SAAS;AAC/C,gBAAA,EAAE,qBAAqB,IAAI,GAAG;AAChC,kBAAI,EAAE,aAAa,KAAK,EAAE,GAAG;AAC3B,oBAAI,KAAK,GAAG,SAAS,KAAK,MAAM;AAC9B,uBAAK,OAAO;AACF,4BAAA;AAAA,gBAAA;AAAA,cACZ;AAAA,YACF;AAAA,UACF,CACD;AAAA,QAAA,WACQ,EAAE,sBAAsB,KAAK,KAAK,WAAW,GAAG;AACzD,cAAI,EAAE,aAAa,KAAK,KAAK,YAAY,EAAE,GAAG;AAC5C,gBAAI,KAAK,KAAK,YAAY,GAAG,SAAS,KAAK,MAAM;AAC/C,mBAAK,OAAO;AACF,wBAAA;AAAA,YAAA;AAAA,UACZ;AAAA,QACF;AAAA,MACF;AAAA,IAEJ;AAAA,IACA,yBAAyB,MAAM;AAC7B,UAAI,EAAE,aAAa,KAAK,KAAK,WAAW,GAAG;AACzC,YAAI,KAAK,KAAK,YAAY,SAAS,KAAK,MAAM;AAC5C,eAAK,OAAO;AACF,oBAAA;AAAA,QAAA;AAAA,MACZ;AAAA,IACF;AAAA,EACF,CACD;AAEM,SAAA;AACT;"}
1
+ {"version":3,"file":"compilers.js","sources":["../../../../src/core/code-splitter/compilers.ts"],"sourcesContent":["import * as t from '@babel/types'\nimport babel from '@babel/core'\nimport _generate from '@babel/generator'\nimport * as template from '@babel/template'\nimport { deadCodeElimination } from 'babel-dead-code-elimination'\n\nimport { splitPrefix } from '../constants'\nimport { parseAst } from './ast'\nimport type { ParseAstOptions } from './ast'\n\nconst debug = process.env.TSR_VITE_DEBUG\n\n// Babel is a CJS package and uses `default` as named binding (`exports.default =`).\n// https://github.com/babel/babel/issues/15269.\nlet generate = (_generate as any)['default'] as typeof _generate\n\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nif (!generate) {\n generate = _generate\n}\n\ntype SplitModulesById = Record<\n string,\n { id: string; node: t.FunctionExpression }\n>\n\ninterface State {\n filename: string\n opts: {\n minify: boolean\n root: string\n }\n imported: Record<string, boolean>\n refs: Set<any>\n serverIndex: number\n splitIndex: number\n splitModulesById: SplitModulesById\n}\n\nfunction addSplitSearchParamToFilename(filename: string) {\n const [bareFilename] = filename.split('?')\n return `${bareFilename}?${splitPrefix}`\n}\n\nfunction removeSplitSearchParamFromFilename(filename: string) {\n const [bareFilename] = filename.split('?')\n return bareFilename!\n}\n\nexport function compileCodeSplitReferenceRoute(opts: ParseAstOptions) {\n const ast = parseAst(opts)\n\n babel.traverse(ast, {\n Program: {\n enter(programPath, programState) {\n const state = programState as unknown as State\n\n // We need to extract the existing search params from the filename, if any\n // and add the splitPrefix to them, then write them back to the filename\n const splitUrl = addSplitSearchParamToFilename(opts.filename)\n\n /**\n * If the component for the route is being imported from\n * another file, this is to track the path to that file\n * the path itself doesn't matter, we just need to keep\n * track of it so that we can remove it from the imports\n * list if it's not being used like:\n *\n * `import '../shared/imported'`\n */\n let existingCompImportPath: string | null = null\n let existingLoaderImportPath: string | null = null\n\n programPath.traverse(\n {\n CallExpression: (path) => {\n if (!t.isIdentifier(path.node.callee)) {\n return\n }\n\n if (\n !(\n path.node.callee.name === 'createRoute' ||\n path.node.callee.name === 'createFileRoute'\n )\n ) {\n return\n }\n\n if (t.isCallExpression(path.parentPath.node)) {\n const options = resolveIdentifier(\n path,\n path.parentPath.node.arguments[0],\n )\n\n let found = false\n\n const hasImportedOrDefinedIdentifier = (name: string) => {\n return programPath.scope.hasBinding(name)\n }\n\n if (t.isObjectExpression(options)) {\n options.properties.forEach((prop) => {\n if (t.isObjectProperty(prop)) {\n if (t.isIdentifier(prop.key)) {\n if (prop.key.name === 'component') {\n const value = prop.value\n\n let shouldSplit = true\n\n if (t.isIdentifier(value)) {\n existingCompImportPath =\n getImportSpecifierAndPathFromLocalName(\n programPath,\n value.name,\n ).path\n\n // exported identifiers should not be split\n // since they are already being imported\n // and need to be retained in the compiled file\n const isExported = hasExport(ast, value)\n shouldSplit = !isExported\n\n if (shouldSplit) {\n removeIdentifierLiteral(path, value)\n }\n }\n\n if (shouldSplit) {\n // Prepend the import statement to the program along with the importer function\n // Check to see if lazyRouteComponent is already imported before attempting\n // to import it again\n\n if (\n !hasImportedOrDefinedIdentifier(\n 'lazyRouteComponent',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.statement(\n `import { lazyRouteComponent } from '@tanstack/react-router'`,\n )(),\n ])\n }\n\n if (\n !hasImportedOrDefinedIdentifier(\n '$$splitComponentImporter',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.statement(\n `const $$splitComponentImporter = () => import('${splitUrl}')`,\n )(),\n ])\n }\n\n prop.value = template.expression(\n `lazyRouteComponent($$splitComponentImporter, 'component', () => Route.ssr)`,\n )()\n\n programPath.pushContainer('body', [\n template.statement(\n `function DummyComponent() { return null }`,\n )(),\n ])\n\n found = true\n }\n } else if (prop.key.name === 'loader') {\n const value = prop.value\n\n let shouldSplit = true\n\n if (t.isIdentifier(value)) {\n existingLoaderImportPath =\n getImportSpecifierAndPathFromLocalName(\n programPath,\n value.name,\n ).path\n\n // exported identifiers should not be split\n // since they are already being imported\n // and need to be retained in the compiled file\n const isExported = hasExport(ast, value)\n shouldSplit = !isExported\n\n if (shouldSplit) {\n removeIdentifierLiteral(path, value)\n }\n }\n\n if (shouldSplit) {\n // Prepend the import statement to the program along with the importer function\n if (!hasImportedOrDefinedIdentifier('lazyFn')) {\n programPath.unshiftContainer('body', [\n template.smart(\n `import { lazyFn } from '@tanstack/react-router'`,\n )() as t.Statement,\n ])\n }\n\n if (\n !hasImportedOrDefinedIdentifier(\n '$$splitLoaderImporter',\n )\n ) {\n programPath.unshiftContainer('body', [\n template.statement(\n `const $$splitLoaderImporter = () => import('${splitUrl}')`,\n )(),\n ])\n }\n\n prop.value = template.expression(\n `lazyFn($$splitLoaderImporter, 'loader')`,\n )()\n\n found = true\n }\n }\n }\n }\n\n programPath.scope.crawl()\n })\n }\n\n if (found as boolean) {\n programPath.pushContainer('body', [\n template.statement(`function TSR_Dummy_Component() {}`)(),\n ])\n }\n }\n },\n },\n state,\n )\n\n /**\n * If the component for the route is being imported,\n * and it's not being used, remove the import statement\n * from the program, by checking that the import has no\n * specifiers\n */\n if (\n (existingCompImportPath as string | null) ||\n (existingLoaderImportPath as string | null)\n ) {\n programPath.traverse({\n ImportDeclaration(path) {\n if (path.node.specifiers.length > 0) return\n if (\n path.node.source.value === existingCompImportPath ||\n path.node.source.value === existingLoaderImportPath\n ) {\n path.remove()\n }\n },\n })\n }\n },\n },\n })\n\n deadCodeElimination(ast)\n\n return generate(ast, {\n sourceMaps: true,\n sourceFileName: opts.filename,\n minified: process.env.NODE_ENV === 'production',\n })\n}\n\nconst splitNodeTypes = ['component', 'loader'] as const\ntype SplitNodeType = (typeof splitNodeTypes)[number]\n\nexport function compileCodeSplitVirtualRoute(opts: ParseAstOptions) {\n const ast = parseAst(opts)\n\n const knownExportedIdents = new Set<string>()\n\n babel.traverse(ast, {\n Program: {\n enter(programPath, programState) {\n const state = programState as unknown as State\n\n const splitNodesByType: Record<SplitNodeType, t.Node | undefined> = {\n component: undefined,\n loader: undefined,\n }\n\n // Find the node\n programPath.traverse(\n {\n CallExpression: (path) => {\n if (!t.isIdentifier(path.node.callee)) {\n return\n }\n\n if (\n !(\n path.node.callee.name === 'createRoute' ||\n path.node.callee.name === 'createFileRoute'\n )\n ) {\n return\n }\n\n if (t.isCallExpression(path.parentPath.node)) {\n const options = resolveIdentifier(\n path,\n path.parentPath.node.arguments[0],\n )\n\n if (t.isObjectExpression(options)) {\n options.properties.forEach((prop) => {\n if (t.isObjectProperty(prop)) {\n splitNodeTypes.forEach((splitType) => {\n if (\n !t.isIdentifier(prop.key) ||\n prop.key.name !== splitType\n ) {\n return\n }\n\n const value = prop.value\n\n let isExported = false\n if (t.isIdentifier(value)) {\n isExported = hasExport(ast, value)\n if (isExported) {\n knownExportedIdents.add(value.name)\n }\n }\n\n // If the node is exported, we need to remove\n // the export from the split file\n if (isExported && t.isIdentifier(value)) {\n removeExports(ast, value)\n } else {\n splitNodesByType[splitType] = prop.value\n }\n })\n }\n })\n\n // Remove all of the options\n options.properties = []\n }\n }\n },\n },\n state,\n )\n\n splitNodeTypes.forEach((splitType) => {\n let splitNode = splitNodesByType[splitType]\n\n if (!splitNode) {\n return\n }\n\n while (t.isIdentifier(splitNode)) {\n const binding = programPath.scope.getBinding(splitNode.name)\n splitNode = binding?.path.node\n }\n\n // Add the node to the program\n if (splitNode) {\n if (t.isFunctionDeclaration(splitNode)) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(splitType),\n t.functionExpression(\n splitNode.id || null, // Anonymize the function expression\n splitNode.params,\n splitNode.body,\n splitNode.generator,\n splitNode.async,\n ),\n ),\n ]),\n )\n } else if (\n t.isFunctionExpression(splitNode) ||\n t.isArrowFunctionExpression(splitNode)\n ) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(splitType),\n splitNode as any,\n ),\n ]),\n )\n } else if (\n t.isImportSpecifier(splitNode) ||\n t.isImportDefaultSpecifier(splitNode)\n ) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(splitType),\n splitNode.local,\n ),\n ]),\n )\n } else if (t.isVariableDeclarator(splitNode)) {\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(t.identifier(splitType), splitNode.init),\n ]),\n )\n } else if (t.isCallExpression(splitNode)) {\n const outputSplitNodeCode = generate(splitNode).code\n const splitNodeAst = babel.parse(outputSplitNodeCode)\n\n if (!splitNodeAst) {\n throw new Error(\n `Failed to parse the generated code for \"${splitType}\" in the node type \"${splitNode.type}\"`,\n )\n }\n\n const statement = splitNodeAst.program.body[0]\n\n if (!statement) {\n throw new Error(\n `Failed to parse the generated code for \"${splitType}\" in the node type \"${splitNode.type}\" as no statement was found in the program body`,\n )\n }\n\n if (t.isExpressionStatement(statement)) {\n const expression = statement.expression\n programPath.pushContainer(\n 'body',\n t.variableDeclaration('const', [\n t.variableDeclarator(t.identifier(splitType), expression),\n ]),\n )\n } else {\n throw new Error(\n `Unexpected expression type encounter for \"${splitType}\" in the node type \"${splitNode.type}\"`,\n )\n }\n } else {\n console.info('Unexpected splitNode type:', splitNode)\n throw new Error(`Unexpected splitNode type ☝️: ${splitNode.type}`)\n }\n }\n\n // If the splitNode exists at the top of the program\n // then we need to remove that copy\n programPath.node.body = programPath.node.body.filter((node) => {\n return node !== splitNode\n })\n\n // Export the node\n programPath.pushContainer('body', [\n t.exportNamedDeclaration(null, [\n t.exportSpecifier(\n t.identifier(splitType),\n t.identifier(splitType),\n ),\n ]),\n ])\n })\n\n // convert exports to imports from the original file\n programPath.traverse({\n ExportNamedDeclaration(path) {\n // e.g. export const x = 1 or export { x }\n // becomes\n // import { x } from '${opts.id}'\n\n if (path.node.declaration) {\n if (t.isVariableDeclaration(path.node.declaration)) {\n path.replaceWith(\n t.importDeclaration(\n path.node.declaration.declarations.map((decl) =>\n t.importSpecifier(\n t.identifier((decl.id as any).name),\n t.identifier((decl.id as any).name),\n ),\n ),\n t.stringLiteral(\n removeSplitSearchParamFromFilename(opts.filename),\n ),\n ),\n )\n }\n }\n },\n })\n },\n },\n })\n\n deadCodeElimination(ast)\n\n // if there are exported identifiers, then we need to add a warning\n // to the file to let the user know that the exported identifiers\n // will not in the split file but in the original file, therefore\n // increasing the bundle size\n if (knownExportedIdents.size > 0) {\n const list = Array.from(knownExportedIdents).reduce((str, ident) => {\n str += `\\n- ${ident}`\n return str\n }, '')\n\n 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.`\n console.warn(warningMessage)\n\n // append this warning to the file using a template\n if (process.env.NODE_ENV !== 'production') {\n const warningTemplate = template.statement(\n `console.warn(${JSON.stringify(warningMessage)})`,\n )()\n ast.program.body.unshift(warningTemplate)\n }\n }\n\n return generate(ast, {\n sourceMaps: true,\n sourceFileName: opts.filename,\n minified: process.env.NODE_ENV === 'production',\n })\n}\n\nfunction getImportSpecifierAndPathFromLocalName(\n programPath: babel.NodePath<t.Program>,\n name: string,\n): {\n specifier:\n | t.ImportSpecifier\n | t.ImportDefaultSpecifier\n | t.ImportNamespaceSpecifier\n | null\n path: string | null\n} {\n let specifier:\n | t.ImportSpecifier\n | t.ImportDefaultSpecifier\n | t.ImportNamespaceSpecifier\n | null = null\n let path: string | null = null\n\n programPath.traverse({\n ImportDeclaration(importPath) {\n const found = importPath.node.specifiers.find(\n (targetSpecifier) => targetSpecifier.local.name === name,\n )\n if (found) {\n specifier = found\n path = importPath.node.source.value\n }\n },\n })\n\n return { specifier, path }\n}\n\n// Reusable function to get literal value or resolve variable to literal\nfunction resolveIdentifier(path: any, node: any) {\n if (t.isIdentifier(node)) {\n const binding = path.scope.getBinding(node.name)\n if (\n binding\n // && binding.kind === 'const'\n ) {\n const declarator = binding.path.node\n if (t.isObjectExpression(declarator.init)) {\n return declarator.init\n } else if (t.isFunctionDeclaration(declarator.init)) {\n return declarator.init\n }\n }\n return undefined\n }\n\n return node\n}\n\nfunction removeIdentifierLiteral(path: any, node: any) {\n if (t.isIdentifier(node)) {\n const binding = path.scope.getBinding(node.name)\n if (binding) {\n binding.path.remove()\n }\n }\n}\n\nfunction hasExport(ast: t.File, node: t.Identifier): boolean {\n let found = false\n\n babel.traverse(ast, {\n ExportNamedDeclaration(path) {\n if (path.node.declaration) {\n // declared as `const loaderFn = () => {}`\n if (t.isVariableDeclaration(path.node.declaration)) {\n path.node.declaration.declarations.forEach((decl) => {\n if (t.isVariableDeclarator(decl)) {\n if (t.isIdentifier(decl.id)) {\n if (decl.id.name === node.name) {\n found = true\n }\n }\n }\n })\n }\n\n // declared as `function loaderFn() {}`\n if (t.isFunctionDeclaration(path.node.declaration)) {\n if (t.isIdentifier(path.node.declaration.id)) {\n if (path.node.declaration.id.name === node.name) {\n found = true\n }\n }\n }\n }\n },\n ExportDefaultDeclaration(path) {\n if (t.isIdentifier(path.node.declaration)) {\n if (path.node.declaration.name === node.name) {\n found = true\n }\n }\n },\n })\n\n return found\n}\n\nfunction removeExports(ast: t.File, node: t.Identifier): boolean {\n let removed = false\n\n babel.traverse(ast, {\n ExportNamedDeclaration(path) {\n if (path.node.declaration) {\n // declared as `const loaderFn = () => {}`\n if (t.isVariableDeclaration(path.node.declaration)) {\n path.node.declaration.declarations.forEach((decl) => {\n if (t.isVariableDeclarator(decl)) {\n if (t.isIdentifier(decl.id)) {\n if (decl.id.name === node.name) {\n path.remove()\n removed = true\n }\n }\n }\n })\n } else if (t.isFunctionDeclaration(path.node.declaration)) {\n if (t.isIdentifier(path.node.declaration.id)) {\n if (path.node.declaration.id.name === node.name) {\n path.remove()\n removed = true\n }\n }\n }\n }\n },\n ExportDefaultDeclaration(path) {\n if (t.isIdentifier(path.node.declaration)) {\n if (path.node.declaration.name === node.name) {\n path.remove()\n removed = true\n }\n }\n },\n })\n\n return removed\n}\n"],"names":[],"mappings":";;;;;;;AAUc,QAAQ,IAAI;AAI1B,IAAI,WAAY,UAAkB,SAAS;AAG3C,IAAI,CAAC,UAAU;AACF,aAAA;AACb;AAoBA,SAAS,8BAA8B,UAAkB;AACvD,QAAM,CAAC,YAAY,IAAI,SAAS,MAAM,GAAG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K,WAAW,GAAG;AACzC,YAAI,KAAK,KAAK,YAAY,SAAS,KAAK,MAAM;AACpC,kBAAA;AAAA,QAAA;AAAA,MACV;AAAA,IACF;AAAA,EACF,CACD;AAEM,SAAA;AACT;AAEA,SAAS,cAAc,KAAa,MAA6B;AAC/D,MAAI,UAAU;AAEd,QAAM,SAAS,KAAK;AAAA,IAClB,uBAAuB,MAAM;AACvB,UAAA,KAAK,KAAK,aAAa;AAEzB,YAAI,EAAE,sBAAsB,KAAK,KAAK,WAAW,GAAG;AAClD,eAAK,KAAK,YAAY,aAAa,QAAQ,CAAC,SAAS;AAC/C,gBAAA,EAAE,qBAAqB,IAAI,GAAG;AAChC,kBAAI,EAAE,aAAa,KAAK,EAAE,GAAG;AAC3B,oBAAI,KAAK,GAAG,SAAS,KAAK,MAAM;AAC9B,uBAAK,OAAO;AACF,4BAAA;AAAA,gBAAA;AAAA,cACZ;AAAA,YACF;AAAA,UACF,CACD;AAAA,QAAA,WACQ,EAAE,sBAAsB,KAAK,KAAK,WAAW,GAAG;AACzD,cAAI,EAAE,aAAa,KAAK,KAAK,YAAY,EAAE,GAAG;AAC5C,gBAAI,KAAK,KAAK,YAAY,GAAG,SAAS,KAAK,MAAM;AAC/C,mBAAK,OAAO;AACF,wBAAA;AAAA,YAAA;AAAA,UACZ;AAAA,QACF;AAAA,MACF;AAAA,IAEJ;AAAA,IACA,yBAAyB,MAAM;AAC7B,UAAI,EAAE,aAAa,KAAK,KAAK,WAAW,GAAG;AACzC,YAAI,KAAK,KAAK,YAAY,SAAS,KAAK,MAAM;AAC5C,eAAK,OAAO;AACF,oBAAA;AAAA,QAAA;AAAA,MACZ;AAAA,IACF;AAAA,EACF,CACD;AAEM,SAAA;AACT;"}
@@ -1,8 +1,10 @@
1
1
  import { isAbsolute, join, normalize } from "node:path";
2
2
  import { pathToFileURL, fileURLToPath } from "node:url";
3
+ import { logDiff } from "../logger.js";
3
4
  import { getConfig } from "./config.js";
4
5
  import { compileCodeSplitVirtualRoute, compileCodeSplitReferenceRoute } from "./code-splitter/compilers.js";
5
6
  import { splitPrefix } from "./constants.js";
7
+ const debug = process.env.TSR_VITE_DEBUG && ["true", "router-plugin"].includes(process.env.TSR_VITE_DEBUG);
6
8
  function capitalizeFirst(str) {
7
9
  return str.charAt(0).toUpperCase() + str.slice(1);
8
10
  }
@@ -31,62 +33,38 @@ plugins: [
31
33
  }
32
34
  }
33
35
  const PLUGIN_NAME = "unplugin:router-code-splitter";
34
- const JoinedSplitPrefix = splitPrefix + ":";
35
36
  const unpluginRouterCodeSplitterFactory = (options = {}, { framework }) => {
36
- const debug = Boolean(process.env.TSR_VITE_DEBUG);
37
37
  let ROOT = process.cwd();
38
38
  let userConfig = options;
39
39
  const handleSplittingFile = (code, id) => {
40
- if (debug) console.info("Splitting route: ", id);
41
- if (debug) console.info("");
42
- if (debug) console.info("Split Route Input: ", id);
43
- if (debug) console.info("");
44
- if (debug) console.info(code);
45
- if (debug) console.info("");
46
- if (debug) console.info("");
47
- if (debug) console.info("");
40
+ if (debug) console.info("Splitting Route: ", id);
48
41
  const compiledVirtualRoute = compileCodeSplitVirtualRoute({
49
42
  code,
50
43
  root: ROOT,
51
44
  filename: id
52
45
  });
53
- if (debug) console.info("");
54
- if (debug) console.info("Split Route Output: ", id);
55
- if (debug) console.info("");
56
- if (debug) console.info(compiledVirtualRoute.code);
57
- if (debug) console.info("");
58
- if (debug) console.info("");
59
- if (debug) console.info("");
46
+ if (debug) {
47
+ logDiff(code, compiledVirtualRoute.code);
48
+ console.log("Output:\n", compiledVirtualRoute.code);
49
+ }
60
50
  return compiledVirtualRoute;
61
51
  };
62
52
  const handleCompilingFile = (code, id) => {
63
- if (debug) console.info("Handling createRoute: ", id);
53
+ if (debug) console.info("Compiling Route: ", id);
64
54
  const compiledReferenceRoute = compileCodeSplitReferenceRoute({
65
55
  code,
66
56
  root: ROOT,
67
57
  filename: id
68
58
  });
69
- if (debug) console.info("");
70
- if (debug) console.info("Handling createRoute output: ", id);
71
- if (debug) console.info("");
72
- if (debug) console.info(compiledReferenceRoute.code);
73
- if (debug) console.info("");
74
- if (debug) console.info("");
75
- if (debug) console.info("");
59
+ if (debug) {
60
+ logDiff(code, compiledReferenceRoute.code);
61
+ console.log("Output:\n", compiledReferenceRoute.code + "\n\n");
62
+ }
76
63
  return compiledReferenceRoute;
77
64
  };
78
65
  return {
79
66
  name: "router-code-splitter-plugin",
80
67
  enforce: "pre",
81
- resolveId(source) {
82
- if (!userConfig.autoCodeSplitting) {
83
- return null;
84
- }
85
- if (source.startsWith(splitPrefix + ":")) {
86
- return source.replace(splitPrefix + ":", "");
87
- }
88
- return null;
89
- },
90
68
  transform(code, id) {
91
69
  if (!userConfig.autoCodeSplitting) {
92
70
  return null;
@@ -109,14 +87,10 @@ const unpluginRouterCodeSplitterFactory = (options = {}, { framework }) => {
109
87
  }
110
88
  return null;
111
89
  },
112
- transformInclude(transformId) {
90
+ transformInclude(id) {
113
91
  if (!userConfig.autoCodeSplitting) {
114
92
  return void 0;
115
93
  }
116
- let id = transformId;
117
- if (id.startsWith(JoinedSplitPrefix)) {
118
- id = id.replace(JoinedSplitPrefix, "");
119
- }
120
94
  if (fileIsInRoutesDirectory(id, userConfig.routesDirectory) || id.includes(splitPrefix)) {
121
95
  return true;
122
96
  }
@@ -130,36 +104,10 @@ const unpluginRouterCodeSplitterFactory = (options = {}, { framework }) => {
130
104
  },
131
105
  rspack(compiler) {
132
106
  ROOT = process.cwd();
133
- compiler.hooks.beforeCompile.tap(PLUGIN_NAME, (self) => {
134
- self.normalModuleFactory.hooks.beforeResolve.tap(
135
- PLUGIN_NAME,
136
- (resolveData) => {
137
- if (resolveData.request.includes(JoinedSplitPrefix)) {
138
- resolveData.request = resolveData.request.replace(
139
- JoinedSplitPrefix,
140
- ""
141
- );
142
- }
143
- }
144
- );
145
- });
146
107
  userConfig = getConfig(options, ROOT);
147
108
  },
148
109
  webpack(compiler) {
149
110
  ROOT = process.cwd();
150
- compiler.hooks.beforeCompile.tap(PLUGIN_NAME, (self) => {
151
- self.normalModuleFactory.hooks.beforeResolve.tap(
152
- PLUGIN_NAME,
153
- (resolveData) => {
154
- if (resolveData.request.includes(JoinedSplitPrefix)) {
155
- resolveData.request = resolveData.request.replace(
156
- JoinedSplitPrefix,
157
- ""
158
- );
159
- }
160
- }
161
- );
162
- });
163
111
  userConfig = getConfig(options, ROOT);
164
112
  if (userConfig.autoCodeSplitting && compiler.options.mode === "production") {
165
113
  compiler.hooks.done.tap(PLUGIN_NAME, () => {
@@ -1 +1 @@
1
- {"version":3,"file":"router-code-splitter-plugin.js","sources":["../../../src/core/router-code-splitter-plugin.ts"],"sourcesContent":["import { isAbsolute, join, normalize } from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\n\nimport { getConfig } from './config'\nimport {\n compileCodeSplitReferenceRoute,\n compileCodeSplitVirtualRoute,\n} from './code-splitter/compilers'\nimport { splitPrefix } from './constants'\n\nimport type { Config } from './config'\nimport type { UnpluginContextMeta, UnpluginFactory } from 'unplugin'\n\nfunction capitalizeFirst(str: string): string {\n return str.charAt(0).toUpperCase() + str.slice(1)\n}\n\nfunction fileIsInRoutesDirectory(\n filePath: string,\n routesDirectory: string,\n): boolean {\n const routesDirectoryPath = isAbsolute(routesDirectory)\n ? routesDirectory\n : join(process.cwd(), routesDirectory)\n\n const path = normalize(filePath)\n\n return path.startsWith(routesDirectoryPath)\n}\n\ntype BannedBeforeExternalPlugin = {\n identifier: string\n pkg: string\n usage: string\n frameworks: Array<UnpluginContextMeta['framework']>\n}\n\nconst bannedBeforeExternalPlugins: Array<BannedBeforeExternalPlugin> = [\n {\n identifier: '@react-refresh',\n pkg: '@vitejs/plugin-react',\n usage: 'viteReact()',\n frameworks: ['vite'],\n },\n]\n\nclass FoundPluginInBeforeCode extends Error {\n constructor(externalPlugin: BannedBeforeExternalPlugin, framework: string) {\n super(`We detected that the '${externalPlugin.pkg}' was passed before '@tanstack/router-plugin'. Please make sure that '@tanstack/router-plugin' is passed before '${externalPlugin.pkg}' and try again: \ne.g.\nplugins: [\n TanStackRouter${capitalizeFirst(framework)}(), // Place this before ${externalPlugin.usage}\n ${externalPlugin.usage},\n]\n`)\n }\n}\n\nconst PLUGIN_NAME = 'unplugin:router-code-splitter'\nconst JoinedSplitPrefix = splitPrefix + ':'\n\nexport const unpluginRouterCodeSplitterFactory: UnpluginFactory<\n Partial<Config> | undefined\n> = (options = {}, { framework }) => {\n const debug = Boolean(process.env.TSR_VITE_DEBUG)\n\n let ROOT: string = process.cwd()\n let userConfig = options as Config\n\n const handleSplittingFile = (code: string, id: string) => {\n if (debug) console.info('Splitting route: ', id)\n\n if (debug) console.info('')\n if (debug) console.info('Split Route Input: ', id)\n if (debug) console.info('')\n if (debug) console.info(code)\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n\n const compiledVirtualRoute = compileCodeSplitVirtualRoute({\n code,\n root: ROOT,\n filename: id,\n })\n\n if (debug) console.info('')\n if (debug) console.info('Split Route Output: ', id)\n if (debug) console.info('')\n if (debug) console.info(compiledVirtualRoute.code)\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n\n return compiledVirtualRoute\n }\n\n const handleCompilingFile = (code: string, id: string) => {\n if (debug) console.info('Handling createRoute: ', id)\n\n const compiledReferenceRoute = compileCodeSplitReferenceRoute({\n code,\n root: ROOT,\n filename: id,\n })\n\n if (debug) console.info('')\n if (debug) console.info('Handling createRoute output: ', id)\n if (debug) console.info('')\n if (debug) console.info(compiledReferenceRoute.code)\n if (debug) console.info('')\n if (debug) console.info('')\n if (debug) console.info('')\n\n return compiledReferenceRoute\n }\n\n return {\n name: 'router-code-splitter-plugin',\n enforce: 'pre',\n\n resolveId(source) {\n if (!userConfig.autoCodeSplitting) {\n return null\n }\n\n if (source.startsWith(splitPrefix + ':')) {\n return source.replace(splitPrefix + ':', '')\n }\n return null\n },\n\n transform(code, id) {\n if (!userConfig.autoCodeSplitting) {\n return null\n }\n\n const url = pathToFileURL(id)\n url.searchParams.delete('v')\n id = fileURLToPath(url).replace(/\\\\/g, '/')\n\n if (id.includes(splitPrefix)) {\n return handleSplittingFile(code, id)\n } else if (\n fileIsInRoutesDirectory(id, userConfig.routesDirectory) &&\n (code.includes('createRoute(') || code.includes('createFileRoute('))\n ) {\n for (const externalPlugin of bannedBeforeExternalPlugins) {\n if (!externalPlugin.frameworks.includes(framework)) {\n continue\n }\n\n if (code.includes(externalPlugin.identifier)) {\n throw new FoundPluginInBeforeCode(externalPlugin, framework)\n }\n }\n\n return handleCompilingFile(code, id)\n }\n\n return null\n },\n\n transformInclude(transformId) {\n if (!userConfig.autoCodeSplitting) {\n return undefined\n }\n\n let id = transformId\n\n if (id.startsWith(JoinedSplitPrefix)) {\n id = id.replace(JoinedSplitPrefix, '')\n }\n\n if (\n fileIsInRoutesDirectory(id, userConfig.routesDirectory) ||\n id.includes(splitPrefix)\n ) {\n return true\n }\n return false\n },\n\n vite: {\n configResolved(config) {\n ROOT = config.root\n\n userConfig = getConfig(options, ROOT)\n },\n },\n\n rspack(compiler) {\n ROOT = process.cwd()\n\n compiler.hooks.beforeCompile.tap(PLUGIN_NAME, (self) => {\n self.normalModuleFactory.hooks.beforeResolve.tap(\n PLUGIN_NAME,\n (resolveData: { request: string }) => {\n if (resolveData.request.includes(JoinedSplitPrefix)) {\n resolveData.request = resolveData.request.replace(\n JoinedSplitPrefix,\n '',\n )\n }\n },\n )\n })\n\n userConfig = getConfig(options, ROOT)\n },\n\n webpack(compiler) {\n ROOT = process.cwd()\n\n compiler.hooks.beforeCompile.tap(PLUGIN_NAME, (self) => {\n self.normalModuleFactory.hooks.beforeResolve.tap(\n PLUGIN_NAME,\n (resolveData: { request: string }) => {\n if (resolveData.request.includes(JoinedSplitPrefix)) {\n resolveData.request = resolveData.request.replace(\n JoinedSplitPrefix,\n '',\n )\n }\n },\n )\n })\n\n userConfig = getConfig(options, ROOT)\n\n if (\n userConfig.autoCodeSplitting &&\n compiler.options.mode === 'production'\n ) {\n compiler.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AY,QAAQ,SAAS,iBAAiB,GAAG;AACvC,0BAAA,UAAU,YAAY,QAAQ;AAAA,gBACxC;AAAA,gBACA;AAAA,cACF;AAAA,YAAA;AAAA,UACF;AAAA,QAEJ;AAAA,MAAA,CACD;AAEY,mBAAA,UAAU,SAAS,IAAI;AAAA,IACtC;AAAA,IAEA,QAAQ,UAAU;AAChB,aAAO,QAAQ,IAAI;AAEnB,eAAS,MAAM,cAAc,IAAI,aAAa,CAAC,SAAS;AACjD,aAAA,oBAAoB,MAAM,cAAc;AAAA,UAC3C;AAAA,UACA,CAAC,gBAAqC;AACpC,gBAAI,YAAY,QAAQ,SAAS,iBAAiB,GAAG;AACvC,0BAAA,UAAU,YAAY,QAAQ;AAAA,gBACxC;AAAA,gBACA;AAAA,cACF;AAAA,YAAA;AAAA,UACF;AAAA,QAEJ;AAAA,MAAA,CACD;AAEY,mBAAA,UAAU,SAAS,IAAI;AAEpC,UACE,WAAW,qBACX,SAAS,QAAQ,SAAS,cAC1B;AACA,iBAAS,MAAM,KAAK,IAAI,aAAa,MAAM;AACjC,kBAAA,KAAK,OAAO,cAAc,wBAAwB;AAC1D,qBAAW,MAAM;AACf,oBAAQ,KAAK,CAAC;AAAA,UAAA,CACf;AAAA,QAAA,CACF;AAAA,MAAA;AAAA,IACH;AAAA,EAEJ;AACF;"}
1
+ {"version":3,"file":"router-code-splitter-plugin.js","sources":["../../../src/core/router-code-splitter-plugin.ts"],"sourcesContent":["import { isAbsolute, join, normalize } from 'node:path'\n\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { logDiff } from '../logger'\nimport { getConfig } from './config'\nimport {\n compileCodeSplitReferenceRoute,\n compileCodeSplitVirtualRoute,\n} from './code-splitter/compilers'\nimport { splitPrefix } from './constants'\n\nimport type { Config } from './config'\nimport type { UnpluginContextMeta, UnpluginFactory } from 'unplugin'\n\nconst debug =\n process.env.TSR_VITE_DEBUG &&\n ['true', 'router-plugin'].includes(process.env.TSR_VITE_DEBUG)\n\nfunction capitalizeFirst(str: string): string {\n return str.charAt(0).toUpperCase() + str.slice(1)\n}\n\nfunction fileIsInRoutesDirectory(\n filePath: string,\n routesDirectory: string,\n): boolean {\n const routesDirectoryPath = isAbsolute(routesDirectory)\n ? routesDirectory\n : join(process.cwd(), routesDirectory)\n\n const path = normalize(filePath)\n\n return path.startsWith(routesDirectoryPath)\n}\n\ntype BannedBeforeExternalPlugin = {\n identifier: string\n pkg: string\n usage: string\n frameworks: Array<UnpluginContextMeta['framework']>\n}\n\nconst bannedBeforeExternalPlugins: Array<BannedBeforeExternalPlugin> = [\n {\n identifier: '@react-refresh',\n pkg: '@vitejs/plugin-react',\n usage: 'viteReact()',\n frameworks: ['vite'],\n },\n]\n\nclass FoundPluginInBeforeCode extends Error {\n constructor(externalPlugin: BannedBeforeExternalPlugin, framework: string) {\n super(`We detected that the '${externalPlugin.pkg}' was passed before '@tanstack/router-plugin'. Please make sure that '@tanstack/router-plugin' is passed before '${externalPlugin.pkg}' and try again: \ne.g.\nplugins: [\n TanStackRouter${capitalizeFirst(framework)}(), // Place this before ${externalPlugin.usage}\n ${externalPlugin.usage},\n]\n`)\n }\n}\n\nconst PLUGIN_NAME = 'unplugin:router-code-splitter'\n\nexport const unpluginRouterCodeSplitterFactory: UnpluginFactory<\n Partial<Config> | undefined\n> = (options = {}, { framework }) => {\n let ROOT: string = process.cwd()\n let userConfig = options as Config\n\n const handleSplittingFile = (code: string, id: string) => {\n if (debug) console.info('Splitting Route: ', id)\n\n const compiledVirtualRoute = compileCodeSplitVirtualRoute({\n code,\n root: ROOT,\n filename: id,\n })\n\n if (debug) {\n logDiff(code, compiledVirtualRoute.code)\n console.log('Output:\\n', compiledVirtualRoute.code)\n }\n\n return compiledVirtualRoute\n }\n\n const handleCompilingFile = (code: string, id: string) => {\n if (debug) console.info('Compiling Route: ', id)\n\n const compiledReferenceRoute = compileCodeSplitReferenceRoute({\n code,\n root: ROOT,\n filename: id,\n })\n\n if (debug) {\n logDiff(code, compiledReferenceRoute.code)\n console.log('Output:\\n', compiledReferenceRoute.code + '\\n\\n')\n }\n\n return compiledReferenceRoute\n }\n\n return {\n name: 'router-code-splitter-plugin',\n enforce: 'pre',\n\n transform(code, id) {\n if (!userConfig.autoCodeSplitting) {\n return null\n }\n\n const url = pathToFileURL(id)\n url.searchParams.delete('v')\n id = fileURLToPath(url).replace(/\\\\/g, '/')\n\n if (id.includes(splitPrefix)) {\n return handleSplittingFile(code, id)\n } else if (\n fileIsInRoutesDirectory(id, userConfig.routesDirectory) &&\n (code.includes('createRoute(') || code.includes('createFileRoute('))\n ) {\n for (const externalPlugin of bannedBeforeExternalPlugins) {\n if (!externalPlugin.frameworks.includes(framework)) {\n continue\n }\n\n if (code.includes(externalPlugin.identifier)) {\n throw new FoundPluginInBeforeCode(externalPlugin, framework)\n }\n }\n\n return handleCompilingFile(code, id)\n }\n\n return null\n },\n\n transformInclude(id) {\n if (!userConfig.autoCodeSplitting) {\n return undefined\n }\n\n if (\n fileIsInRoutesDirectory(id, userConfig.routesDirectory) ||\n id.includes(splitPrefix)\n ) {\n return true\n }\n return false\n },\n\n vite: {\n configResolved(config) {\n ROOT = config.root\n\n userConfig = getConfig(options, ROOT)\n },\n },\n\n rspack(compiler) {\n ROOT = process.cwd()\n userConfig = getConfig(options, ROOT)\n },\n\n webpack(compiler) {\n ROOT = process.cwd()\n userConfig = getConfig(options, ROOT)\n\n if (\n userConfig.autoCodeSplitting &&\n compiler.options.mode === 'production'\n ) {\n compiler.hooks.done.tap(PLUGIN_NAME, () => {\n console.info('✅ ' + PLUGIN_NAME + ': code-splitting done!')\n setTimeout(() => {\n process.exit(0)\n })\n })\n }\n },\n }\n}\n"],"names":[],"mappings":";;;;;;AAcA,MAAM,QACJ,QAAQ,IAAI,kBACZ,CAAC,QAAQ,eAAe,EAAE,SAAS,QAAQ,IAAI,cAAc;AAE/D,SAAS,gBAAgB,KAAqB;AACrC,SAAA,IAAI,OAAO,CAAC,EAAE,gBAAgB,IAAI,MAAM,CAA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UACE,WAAW,qBACX,SAAS,QAAQ,SAAS,cAC1B;AACA,iBAAS,MAAM,KAAK,IAAI,aAAa,MAAM;AACjC,kBAAA,KAAK,OAAO,cAAc,wBAAwB;AAC1D,qBAAW,MAAM;AACf,oBAAQ,KAAK,CAAC;AAAA,UAAA,CACf;AAAA,QAAA,CACF;AAAA,MAAA;AAAA,IACH;AAAA,EAEJ;AACF;"}
@@ -0,0 +1 @@
1
+ export declare function logDiff(oldStr: string, newStr: string): void;
@@ -0,0 +1,55 @@
1
+ import chalk from "chalk";
2
+ import { diffWords } from "diff";
3
+ function logDiff(oldStr, newStr) {
4
+ const differences = diffWords(oldStr, newStr);
5
+ let output = "";
6
+ let unchangedLines = "";
7
+ function processUnchangedLines(lines) {
8
+ const lineArray = lines.split("\n");
9
+ if (lineArray.length > 4) {
10
+ return [
11
+ chalk.dim(lineArray[0]),
12
+ chalk.dim(lineArray[1]),
13
+ "",
14
+ chalk.dim.bold(`... (${lineArray.length - 4} lines) ...`),
15
+ "",
16
+ chalk.dim(lineArray[lineArray.length - 2]),
17
+ chalk.dim(lineArray[lineArray.length - 1])
18
+ ].join("\n");
19
+ }
20
+ return chalk.dim(lines);
21
+ }
22
+ differences.forEach((part, index) => {
23
+ const nextPart = differences[index + 1];
24
+ if (part.added) {
25
+ if (unchangedLines) {
26
+ output += processUnchangedLines(unchangedLines);
27
+ unchangedLines = "";
28
+ }
29
+ output += chalk.green.bold(part.value);
30
+ if (nextPart == null ? void 0 : nextPart.removed) output += " ";
31
+ } else if (part.removed) {
32
+ if (unchangedLines) {
33
+ output += processUnchangedLines(unchangedLines);
34
+ unchangedLines = "";
35
+ }
36
+ output += chalk.red.bold(part.value);
37
+ if (nextPart == null ? void 0 : nextPart.added) output += " ";
38
+ } else {
39
+ unchangedLines += part.value;
40
+ }
41
+ });
42
+ if (unchangedLines) {
43
+ output += processUnchangedLines(unchangedLines);
44
+ }
45
+ if (output) {
46
+ console.log("\nDiff:");
47
+ console.log(output + "\n");
48
+ } else {
49
+ console.log("No changes");
50
+ }
51
+ }
52
+ export {
53
+ logDiff
54
+ };
55
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.js","sources":["../../src/logger.ts"],"sourcesContent":["import chalk from 'chalk'\nimport { diffWords } from 'diff'\n\nexport function logDiff(oldStr: string, newStr: string) {\n const differences = diffWords(oldStr, newStr)\n\n let output = ''\n let unchangedLines = ''\n\n function processUnchangedLines(lines: string): string {\n const lineArray = lines.split('\\n')\n if (lineArray.length > 4) {\n return [\n chalk.dim(lineArray[0]),\n chalk.dim(lineArray[1]),\n '',\n chalk.dim.bold(`... (${lineArray.length - 4} lines) ...`),\n '',\n chalk.dim(lineArray[lineArray.length - 2]),\n chalk.dim(lineArray[lineArray.length - 1]),\n ].join('\\n')\n }\n return chalk.dim(lines)\n }\n\n differences.forEach((part, index) => {\n const nextPart = differences[index + 1]\n\n if (part.added) {\n if (unchangedLines) {\n output += processUnchangedLines(unchangedLines)\n unchangedLines = ''\n }\n output += chalk.green.bold(part.value)\n if (nextPart?.removed) output += ' '\n } else if (part.removed) {\n if (unchangedLines) {\n output += processUnchangedLines(unchangedLines)\n unchangedLines = ''\n }\n output += chalk.red.bold(part.value)\n if (nextPart?.added) output += ' '\n } else {\n unchangedLines += part.value\n }\n })\n\n // Process any remaining unchanged lines at the end\n if (unchangedLines) {\n output += processUnchangedLines(unchangedLines)\n }\n\n if (output) {\n console.log('\\nDiff:')\n console.log(output + '\\n')\n } else {\n console.log('No changes')\n }\n}\n"],"names":[],"mappings":";;AAGgB,SAAA,QAAQ,QAAgB,QAAgB;AAChD,QAAA,cAAc,UAAU,QAAQ,MAAM;AAE5C,MAAI,SAAS;AACb,MAAI,iBAAiB;AAErB,WAAS,sBAAsB,OAAuB;AAC9C,UAAA,YAAY,MAAM,MAAM,IAAI;AAC9B,QAAA,UAAU,SAAS,GAAG;AACjB,aAAA;AAAA,QACL,MAAM,IAAI,UAAU,CAAC,CAAC;AAAA,QACtB,MAAM,IAAI,UAAU,CAAC,CAAC;AAAA,QACtB;AAAA,QACA,MAAM,IAAI,KAAK,QAAQ,UAAU,SAAS,CAAC,aAAa;AAAA,QACxD;AAAA,QACA,MAAM,IAAI,UAAU,UAAU,SAAS,CAAC,CAAC;AAAA,QACzC,MAAM,IAAI,UAAU,UAAU,SAAS,CAAC,CAAC;AAAA,MAAA,EACzC,KAAK,IAAI;AAAA,IAAA;AAEN,WAAA,MAAM,IAAI,KAAK;AAAA,EAAA;AAGZ,cAAA,QAAQ,CAAC,MAAM,UAAU;AAC7B,UAAA,WAAW,YAAY,QAAQ,CAAC;AAEtC,QAAI,KAAK,OAAO;AACd,UAAI,gBAAgB;AAClB,kBAAU,sBAAsB,cAAc;AAC7B,yBAAA;AAAA,MAAA;AAEnB,gBAAU,MAAM,MAAM,KAAK,KAAK,KAAK;AACjC,UAAA,qCAAU,QAAmB,WAAA;AAAA,IAAA,WACxB,KAAK,SAAS;AACvB,UAAI,gBAAgB;AAClB,kBAAU,sBAAsB,cAAc;AAC7B,yBAAA;AAAA,MAAA;AAEnB,gBAAU,MAAM,IAAI,KAAK,KAAK,KAAK;AAC/B,UAAA,qCAAU,MAAiB,WAAA;AAAA,IAAA,OAC1B;AACL,wBAAkB,KAAK;AAAA,IAAA;AAAA,EACzB,CACD;AAGD,MAAI,gBAAgB;AAClB,cAAU,sBAAsB,cAAc;AAAA,EAAA;AAGhD,MAAI,QAAQ;AACV,YAAQ,IAAI,SAAS;AACb,YAAA,IAAI,SAAS,IAAI;AAAA,EAAA,OACpB;AACL,YAAQ,IAAI,YAAY;AAAA,EAAA;AAE5B;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/router-plugin",
3
- "version": "1.95.6",
3
+ "version": "1.96.0",
4
4
  "description": "Modern and scalable routing for React applications",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -86,22 +86,25 @@
86
86
  "node": ">=12"
87
87
  },
88
88
  "dependencies": {
89
+ "@babel/core": "^7.26.0",
90
+ "@babel/generator": "^7.26.3",
91
+ "@babel/parser": "^7.26.3",
89
92
  "@babel/plugin-syntax-jsx": "^7.25.9",
93
+ "@babel/plugin-syntax-typescript": "^7.25.9",
90
94
  "@babel/template": "^7.25.9",
95
+ "@babel/traverse": "^7.26.4",
96
+ "@babel/types": "^7.26.3",
91
97
  "@types/babel__core": "^7.20.5",
92
98
  "@types/babel__generator": "^7.6.8",
93
99
  "@types/babel__template": "^7.4.4",
94
100
  "@types/babel__traverse": "^7.20.6",
101
+ "@types/diff": "^6.0.0",
95
102
  "babel-dead-code-elimination": "^1.0.8",
103
+ "chalk": "^5.3.0",
96
104
  "chokidar": "^3.6.0",
105
+ "diff": "^7.0.0",
97
106
  "unplugin": "^1.16.0",
98
107
  "zod": "^3.23.8",
99
- "@babel/generator": "^7.26.3",
100
- "@babel/core": "^7.26.0",
101
- "@babel/parser": "^7.26.3",
102
- "@babel/plugin-syntax-typescript": "^7.25.9",
103
- "@babel/traverse": "^7.26.4",
104
- "@babel/types": "^7.26.3",
105
108
  "@tanstack/router-generator": "^1.95.6",
106
109
  "@tanstack/virtual-file-routes": "^1.87.6"
107
110
  },
@@ -37,6 +37,16 @@ interface State {
37
37
  splitModulesById: SplitModulesById
38
38
  }
39
39
 
40
+ function addSplitSearchParamToFilename(filename: string) {
41
+ const [bareFilename] = filename.split('?')
42
+ return `${bareFilename}?${splitPrefix}`
43
+ }
44
+
45
+ function removeSplitSearchParamFromFilename(filename: string) {
46
+ const [bareFilename] = filename.split('?')
47
+ return bareFilename!
48
+ }
49
+
40
50
  export function compileCodeSplitReferenceRoute(opts: ParseAstOptions) {
41
51
  const ast = parseAst(opts)
42
52
 
@@ -45,7 +55,9 @@ export function compileCodeSplitReferenceRoute(opts: ParseAstOptions) {
45
55
  enter(programPath, programState) {
46
56
  const state = programState as unknown as State
47
57
 
48
- const splitUrl = `${splitPrefix}:${opts.filename}?${splitPrefix}`
58
+ // We need to extract the existing search params from the filename, if any
59
+ // and add the splitPrefix to them, then write them back to the filename
60
+ const splitUrl = addSplitSearchParamToFilename(opts.filename)
49
61
 
50
62
  /**
51
63
  * If the component for the route is being imported from
@@ -251,25 +263,12 @@ export function compileCodeSplitReferenceRoute(opts: ParseAstOptions) {
251
263
  },
252
264
  })
253
265
 
254
- if (debug) console.info('')
255
- if (debug) console.info('Dead Code Elimination Input 1:')
256
- if (debug) console.info(generate(ast, { sourceMaps: true }).code)
257
- if (debug) console.info('')
258
- if (debug) console.info('')
259
- if (debug) console.info('')
260
-
261
266
  deadCodeElimination(ast)
262
267
 
263
- if (debug) console.info('')
264
- if (debug) console.info('Dead Code Elimination Output 1:')
265
- if (debug) console.info(generate(ast, { sourceMaps: true }).code)
266
- if (debug) console.info('')
267
- if (debug) console.info('')
268
- if (debug) console.info('')
269
-
270
268
  return generate(ast, {
271
269
  sourceMaps: true,
272
270
  sourceFileName: opts.filename,
271
+ minified: process.env.NODE_ENV === 'production',
273
272
  })
274
273
  }
275
274
 
@@ -490,7 +489,7 @@ export function compileCodeSplitVirtualRoute(opts: ParseAstOptions) {
490
489
  ),
491
490
  ),
492
491
  t.stringLiteral(
493
- opts.filename.split(`?${splitPrefix}`)[0] as string,
492
+ removeSplitSearchParamFromFilename(opts.filename),
494
493
  ),
495
494
  ),
496
495
  )
@@ -502,22 +501,8 @@ export function compileCodeSplitVirtualRoute(opts: ParseAstOptions) {
502
501
  },
503
502
  })
504
503
 
505
- if (debug) console.info('')
506
- if (debug) console.info('Dead Code Elimination Input 2:')
507
- if (debug) console.info(generate(ast, { sourceMaps: true }).code)
508
- if (debug) console.info('')
509
- if (debug) console.info('')
510
- if (debug) console.info('')
511
-
512
504
  deadCodeElimination(ast)
513
505
 
514
- if (debug) console.info('')
515
- if (debug) console.info('Dead Code Elimination Output 2:')
516
- if (debug) console.info(generate(ast, { sourceMaps: true }).code)
517
- if (debug) console.info('')
518
- if (debug) console.info('')
519
- if (debug) console.info('')
520
-
521
506
  // if there are exported identifiers, then we need to add a warning
522
507
  // to the file to let the user know that the exported identifiers
523
508
  // will not in the split file but in the original file, therefore
@@ -543,6 +528,7 @@ export function compileCodeSplitVirtualRoute(opts: ParseAstOptions) {
543
528
  return generate(ast, {
544
529
  sourceMaps: true,
545
530
  sourceFileName: opts.filename,
531
+ minified: process.env.NODE_ENV === 'production',
546
532
  })
547
533
  }
548
534