This commit is contained in:
2026-04-12 01:02:14 +08:00
parent 509487f155
commit 9b053e302b
14085 changed files with 2680009 additions and 12 deletions

View File

@@ -0,0 +1,54 @@
import Module from 'node:module';
import { readFileSync } from 'node:fs';
import { dirname } from 'node:path';
const oldJSHook = require.extensions['.js'];
const extensions = [
'.ts',
'.cts',
'.mts',
'.cjs',
'.mjs'
];
export function registerHook(swcOptions) {
// lazy require swc since it loads React before even setting NODE_ENV
// resulting loading Development React on Production
const { transformSync } = require('../swc');
require.extensions['.js'] = function(mod, oldFilename) {
try {
return oldJSHook(mod, oldFilename);
} catch (error) {
if (error.code !== 'ERR_REQUIRE_ESM') {
throw error;
}
// calling oldJSHook throws ERR_REQUIRE_ESM, so run _compile manually
// TODO: investigate if we can remove readFileSync
const content = readFileSync(oldFilename, 'utf8');
const { code } = transformSync(content, swcOptions);
mod._compile(code, oldFilename);
}
};
for (const ext of extensions){
const oldHook = require.extensions[ext] ?? oldJSHook;
require.extensions[ext] = function(mod, oldFilename) {
const _compile = mod._compile;
mod._compile = function(code, filename) {
const swc = transformSync(code, swcOptions);
return _compile.call(this, swc.code, filename);
};
return oldHook(mod, oldFilename);
};
}
}
export function deregisterHook() {
require.extensions['.js'] = oldJSHook;
extensions.forEach((ext)=>delete require.extensions[ext]);
}
export function requireFromString(code, filename) {
const paths = Module._nodeModulePaths(dirname(filename));
const m = new Module(filename, module.parent);
m.paths = paths;
m._compile(code, filename);
return m.exports;
}
//# sourceMappingURL=require-hook.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/next-config-ts/require-hook.ts"],"sourcesContent":["import type { Options as SWCOptions } from '@swc/core'\nimport Module from 'node:module'\nimport { readFileSync } from 'node:fs'\nimport { dirname } from 'node:path'\n\nconst oldJSHook = require.extensions['.js']\nconst extensions = ['.ts', '.cts', '.mts', '.cjs', '.mjs']\n\nexport function registerHook(swcOptions: SWCOptions) {\n // lazy require swc since it loads React before even setting NODE_ENV\n // resulting loading Development React on Production\n const { transformSync } = require('../swc') as typeof import('../swc')\n\n require.extensions['.js'] = function (mod: any, oldFilename) {\n try {\n return oldJSHook(mod, oldFilename)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ERR_REQUIRE_ESM') {\n throw error\n }\n\n // calling oldJSHook throws ERR_REQUIRE_ESM, so run _compile manually\n // TODO: investigate if we can remove readFileSync\n const content = readFileSync(oldFilename, 'utf8')\n const { code } = transformSync(content, swcOptions)\n mod._compile(code, oldFilename)\n }\n }\n\n for (const ext of extensions) {\n const oldHook = require.extensions[ext] ?? oldJSHook\n require.extensions[ext] = function (mod: any, oldFilename) {\n const _compile = mod._compile\n\n mod._compile = function (code: string, filename: string) {\n const swc = transformSync(code, swcOptions)\n return _compile.call(this, swc.code, filename)\n }\n\n return oldHook(mod, oldFilename)\n }\n }\n}\n\nexport function deregisterHook() {\n require.extensions['.js'] = oldJSHook\n extensions.forEach((ext) => delete require.extensions[ext])\n}\n\nexport function requireFromString(code: string, filename: string) {\n const paths = (Module as any)._nodeModulePaths(dirname(filename))\n const m = new Module(filename, module.parent!) as any\n m.paths = paths\n m._compile(code, filename)\n return m.exports\n}\n"],"names":["Module","readFileSync","dirname","oldJSHook","require","extensions","registerHook","swcOptions","transformSync","mod","oldFilename","error","code","content","_compile","ext","oldHook","filename","swc","call","deregisterHook","forEach","requireFromString","paths","_nodeModulePaths","m","module","parent","exports"],"mappings":"AACA,OAAOA,YAAY,cAAa;AAChC,SAASC,YAAY,QAAQ,UAAS;AACtC,SAASC,OAAO,QAAQ,YAAW;AAEnC,MAAMC,YAAYC,QAAQC,UAAU,CAAC,MAAM;AAC3C,MAAMA,aAAa;IAAC;IAAO;IAAQ;IAAQ;IAAQ;CAAO;AAE1D,OAAO,SAASC,aAAaC,UAAsB;IACjD,qEAAqE;IACrE,oDAAoD;IACpD,MAAM,EAAEC,aAAa,EAAE,GAAGJ,QAAQ;IAElCA,QAAQC,UAAU,CAAC,MAAM,GAAG,SAAUI,GAAQ,EAAEC,WAAW;QACzD,IAAI;YACF,OAAOP,UAAUM,KAAKC;QACxB,EAAE,OAAOC,OAAO;YACd,IAAI,AAACA,MAAgCC,IAAI,KAAK,mBAAmB;gBAC/D,MAAMD;YACR;YAEA,qEAAqE;YACrE,kDAAkD;YAClD,MAAME,UAAUZ,aAAaS,aAAa;YAC1C,MAAM,EAAEE,IAAI,EAAE,GAAGJ,cAAcK,SAASN;YACxCE,IAAIK,QAAQ,CAACF,MAAMF;QACrB;IACF;IAEA,KAAK,MAAMK,OAAOV,WAAY;QAC5B,MAAMW,UAAUZ,QAAQC,UAAU,CAACU,IAAI,IAAIZ;QAC3CC,QAAQC,UAAU,CAACU,IAAI,GAAG,SAAUN,GAAQ,EAAEC,WAAW;YACvD,MAAMI,WAAWL,IAAIK,QAAQ;YAE7BL,IAAIK,QAAQ,GAAG,SAAUF,IAAY,EAAEK,QAAgB;gBACrD,MAAMC,MAAMV,cAAcI,MAAML;gBAChC,OAAOO,SAASK,IAAI,CAAC,IAAI,EAAED,IAAIN,IAAI,EAAEK;YACvC;YAEA,OAAOD,QAAQP,KAAKC;QACtB;IACF;AACF;AAEA,OAAO,SAASU;IACdhB,QAAQC,UAAU,CAAC,MAAM,GAAGF;IAC5BE,WAAWgB,OAAO,CAAC,CAACN,MAAQ,OAAOX,QAAQC,UAAU,CAACU,IAAI;AAC5D;AAEA,OAAO,SAASO,kBAAkBV,IAAY,EAAEK,QAAgB;IAC9D,MAAMM,QAAQ,AAACvB,OAAewB,gBAAgB,CAACtB,QAAQe;IACvD,MAAMQ,IAAI,IAAIzB,OAAOiB,UAAUS,OAAOC,MAAM;IAC5CF,EAAEF,KAAK,GAAGA;IACVE,EAAEX,QAAQ,CAACF,MAAMK;IACjB,OAAOQ,EAAEG,OAAO;AAClB","ignoreList":[0]}

View File

@@ -0,0 +1,98 @@
import { resolve } from 'node:path';
import { readFile } from 'node:fs/promises';
import { deregisterHook, registerHook, requireFromString } from './require-hook';
import { warn } from '../output/log';
import { installDependencies } from '../../lib/install-dependencies';
function resolveSWCOptions(cwd, compilerOptions) {
const resolvedBaseUrl = resolve(cwd, compilerOptions.baseUrl ?? '.');
return {
jsc: {
target: 'es5',
parser: {
syntax: 'typescript'
},
paths: compilerOptions.paths,
baseUrl: resolvedBaseUrl
},
module: {
type: 'commonjs'
},
isModule: 'unknown'
};
}
// Ported from next/src/lib/verify-typescript-setup.ts
// Although this overlaps with the later `verifyTypeScriptSetup`,
// it is acceptable since the time difference in the worst case is trivial,
// as we are only preparing to install the dependencies once more.
async function verifyTypeScriptSetup(cwd, configFileName) {
try {
// Quick module check.
require.resolve('typescript', {
paths: [
cwd
]
});
} catch (error) {
if (error && typeof error === 'object' && 'code' in error && error.code === 'MODULE_NOT_FOUND') {
warn(`Installing TypeScript as it was not found while loading "${configFileName}".`);
await installDependencies(cwd, [
{
pkg: 'typescript'
}
], true).catch((err)=>{
if (err && typeof err === 'object' && 'command' in err) {
console.error(`Failed to install TypeScript, please install it manually to continue:\n` + err.command + '\n');
}
throw err;
});
}
}
}
async function getTsConfig(cwd) {
const ts = require(require.resolve('typescript', {
paths: [
cwd
]
}));
// NOTE: This doesn't fully cover the edge case for setting
// "typescript.tsconfigPath" in next config which is currently
// a restriction.
const tsConfigPath = ts.findConfigFile(cwd, ts.sys.fileExists, 'tsconfig.json');
if (!tsConfigPath) {
// It is ok to not return ts.getDefaultCompilerOptions() because
// we are only lookfing for paths and baseUrl from tsConfig.
return {};
}
const configFile = ts.readConfigFile(tsConfigPath, ts.sys.readFile);
const parsedCommandLine = ts.parseJsonConfigFileContent(configFile.config, ts.sys, cwd);
return parsedCommandLine.options;
}
export async function transpileConfig({ nextConfigPath, configFileName, cwd }) {
let hasRequire = false;
try {
// Ensure TypeScript is installed to use the API.
await verifyTypeScriptSetup(cwd, configFileName);
const compilerOptions = await getTsConfig(cwd);
const swcOptions = resolveSWCOptions(cwd, compilerOptions);
const nextConfigString = await readFile(nextConfigPath, 'utf8');
// lazy require swc since it loads React before even setting NODE_ENV
// resulting loading Development React on Production
const { transform } = require('../swc');
const { code } = await transform(nextConfigString, swcOptions);
// register require hook only if require exists
if (code.includes('require(')) {
registerHook(swcOptions);
hasRequire = true;
}
// filename & extension don't matter here
return requireFromString(code, resolve(cwd, 'next.config.compiled.js'));
} catch (error) {
throw error;
} finally{
if (hasRequire) {
deregisterHook();
}
}
}
//# sourceMappingURL=transpile-config.js.map

File diff suppressed because one or more lines are too long