Skip to content

Commit

Permalink
feat(cjs): support query for cache busting (#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
privatenumber committed Jun 5, 2024
1 parent 585f117 commit e1464cf
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 15 deletions.
19 changes: 11 additions & 8 deletions src/cjs/api/module-extensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,23 +34,26 @@ const transformer = (
module: Module,
filePath: string,
) => {
// Make sure __filename doesnt contain query
const cleanFilePath = filePath.split('?')[0];

// For tracking dependencies in watch mode
if (parent?.send) {
parent.send({
type: 'dependency',
path: filePath,
path: cleanFilePath,
});
}

const transformTs = typescriptExtensions.some(extension => filePath.endsWith(extension));
const transformJs = transformExtensions.some(extension => filePath.endsWith(extension));
const transformTs = typescriptExtensions.some(extension => cleanFilePath.endsWith(extension));
const transformJs = transformExtensions.some(extension => cleanFilePath.endsWith(extension));
if (!transformTs && !transformJs) {
return defaultLoader(module, filePath);
return defaultLoader(module, cleanFilePath);
}

let code = fs.readFileSync(filePath, 'utf8');
let code = fs.readFileSync(cleanFilePath, 'utf8');

if (filePath.endsWith('.cjs')) {
if (cleanFilePath.endsWith('.cjs')) {
// Contains native ESM check
const transformed = transformDynamicImport(filePath, code);
if (transformed) {
Expand All @@ -70,7 +73,7 @@ const transformer = (
code,
filePath,
{
tsconfigRaw: fileMatcher?.(filePath) as TransformOptions['tsconfigRaw'],
tsconfigRaw: fileMatcher?.(cleanFilePath) as TransformOptions['tsconfigRaw'],
},
);

Expand All @@ -81,7 +84,7 @@ const transformer = (
);
}

module._compile(code, filePath);
module._compile(code, cleanFilePath);
};

[
Expand Down
9 changes: 5 additions & 4 deletions src/cjs/api/module-resolve-filename.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export const createResolveFilename = (
) => {
// Strip query string
const queryIndex = request.indexOf('?');
const query = queryIndex === -1 ? '' : request.slice(queryIndex);
if (queryIndex !== -1) {
request = request.slice(0, queryIndex);
}
Expand All @@ -86,7 +87,7 @@ export const createResolveFilename = (
for (const possiblePath of possiblePaths) {
const tsFilename = resolveTsFilename(nextResolve, possiblePath, parent, isMain, options);
if (tsFilename) {
return tsFilename;
return tsFilename + query;
}

try {
Expand All @@ -95,15 +96,15 @@ export const createResolveFilename = (
parent,
isMain,
options,
);
) + query;
} catch {}
}
}

const tsFilename = resolveTsFilename(nextResolve, request, parent, isMain, options);
if (tsFilename) {
return tsFilename;
return tsFilename + query;
}

return nextResolve(request, parent, isMain, options);
return nextResolve(request, parent, isMain, options) + query;
};
7 changes: 4 additions & 3 deletions src/utils/transform/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,17 @@ export const transformSync = (
filePath: string,
extendOptions?: TransformOptions,
): Transformed => {
const [filePathWithoutQuery, query] = filePath.split('?');
const define: { [key: string]: string } = {};

if (!(filePath.endsWith('.cjs') || filePath.endsWith('.cts'))) {
define['import.meta.url'] = JSON.stringify(pathToFileURL(filePath));
if (!(filePathWithoutQuery.endsWith('.cjs') || filePathWithoutQuery.endsWith('.cts'))) {
define['import.meta.url'] = JSON.stringify(pathToFileURL(filePathWithoutQuery) + (query ? `?${query}` : ''));
}

const esbuildOptions = {
...cacheConfig,
format: 'cjs',
sourcefile: filePath,
sourcefile: filePathWithoutQuery,
define,
banner: '(()=>{',
footer: '})()',
Expand Down
4 changes: 4 additions & 0 deletions tests/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,10 @@ export const files = {

'js/index.js': outdent`
import assert from 'assert';
console.log(JSON.stringify({
importMetaUrl: import.meta.url,
__filename: typeof __filename !== 'undefined' ? __filename : undefined,
}));
${syntaxLowering}
${preserveName}
export const cjsContext = ${cjsContextCheck};
Expand Down
13 changes: 13 additions & 0 deletions tests/specs/smoke.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ export default testSuite(async ({ describe }, { tsx }: NodeApis) => {
console.error(error);
console.log(p);
});

expect(p.failed).toBe(false);
expect(p.stdout).toMatch(`"import.meta.url":"${pathToFileURL(fixture.getPath('import-from-js.js'))}"`);
expect(p.stdout).toMatch(`"js":{"cjsContext":${isCommonJs},"default":1,"named":2}`);
Expand All @@ -146,8 +147,14 @@ export default testSuite(async ({ describe }, { tsx }: NodeApis) => {
expect(p.stdout).toMatch('"pkgModule":{"default":1,"named":2}');
if (isCommonJs) {
expect(p.stdout).toMatch('"pkgCommonjs":{"default":1,"named":2}');

expect(p.stdout).toMatch(/\{"importMetaUrl":"file:\/\/\/.+?\/js\/index\.js","__filename":".+?index\.js"\}/);
expect(p.stdout).toMatch(/\{"importMetaUrl":"file:\/\/\/.+?\/js\/index\.js\?query=123","__filename":".+?index\.js"\}/);
} else {
expect(p.stdout).toMatch('"pkgCommonjs":{"default":{"default":1,"named":2}}');

expect(p.stdout).toMatch(/\{"importMetaUrl":"file:\/\/\/.+?\/js\/index\.js"\}/);
expect(p.stdout).toMatch(/\{"importMetaUrl":"file:\/\/\/.+?\/js\/index\.js\?query=123"\}/);
}

// By "require()"ing an ESM file, it forces it to be compiled in a CJS context
Expand Down Expand Up @@ -354,8 +361,14 @@ export default testSuite(async ({ describe }, { tsx }: NodeApis) => {
expect(p.stdout).toMatch('"pkgModule":{"default":1,"named":2}');
if (isCommonJs) {
expect(p.stdout).toMatch('"pkgCommonjs":{"default":1,"named":2}');

expect(p.stdout).toMatch(/\{"importMetaUrl":"file:\/\/\/.+?\/js\/index\.js","__filename":".+?index\.js"\}/);
expect(p.stdout).toMatch(/\{"importMetaUrl":"file:\/\/\/.+?\/js\/index\.js\?query=123","__filename":".+?index\.js"\}/);
} else {
expect(p.stdout).toMatch('"pkgCommonjs":{"default":{"default":1,"named":2}}');

expect(p.stdout).toMatch(/\{"importMetaUrl":"file:\/\/\/.+?\/js\/index\.js"\}/);
expect(p.stdout).toMatch(/\{"importMetaUrl":"file:\/\/\/.+?\/js\/index\.js\?query=123"\}/);
}

// By "require()"ing an ESM file, it forces it to be compiled in a CJS context
Expand Down

0 comments on commit e1464cf

Please sign in to comment.