diff --git a/src/plugins/prerender-plugin.js b/src/plugins/prerender-plugin.js index 5b907de..74af166 100644 --- a/src/plugins/prerender-plugin.js +++ b/src/plugins/prerender-plugin.js @@ -507,10 +507,12 @@ export function prerenderPlugin({ prerenderScript, renderTarget, additionalPrere if (output.endsWith('.js')) { const codeOrSource = bundle[output].type == 'chunk' ? 'code' : 'source'; if (typeof bundle[output][codeOrSource] !== 'string') continue; - bundle[output][codeOrSource] = bundle[output][codeOrSource].replace( - /\n\/\/#\ssourceMappingURL=.*/, - '', - ); + + const linesOfCode = bundle[output][codeOrSource].trimEnd().split('\n'); + if (/^\/\/#\ssourceMappingURL=.*\.map$/.test(linesOfCode.at(-1))) { + linesOfCode.pop(); + bundle[output][codeOrSource] = linesOfCode.join('\n'); + } } } } diff --git a/tests/fixtures/source-maps/src/index.js b/tests/fixtures/source-maps/src/index.js index 8f2e751..caf1dca 100644 --- a/tests/fixtures/source-maps/src/index.js +++ b/tests/fixtures/source-maps/src/index.js @@ -11,3 +11,15 @@ if (typeof window !== 'undefined') { export async function prerender() { return `

Simple Test Result

`; } + +// Basically mirror preact-www's repl worker +const PREPEND = `(function (module, exports) {\n`; +const APPEND = `\n});`; +export async function process() { + const code = `console.log('Hello World');`; + let transpiled = `${PREPEND}${code}${APPEND}`; + + transpiled += '\n//# sourceMappingURL=' + 'some-url.js.map'; + + return transpiled; +} diff --git a/tests/source-maps.test.js b/tests/source-maps.test.js index a648c00..8c4d075 100644 --- a/tests/source-maps.test.js +++ b/tests/source-maps.test.js @@ -32,14 +32,17 @@ test('Should strip sourcemaps by default', async () => { outDirAssets.find((f) => /^index-.*\.js$/.test(f)), ); const outputChunkCode = await fs.readFile(outputChunk, 'utf-8'); - assert.is(outputChunkCode.match(/\/\/#\ssourceMappingURL=(.*)/), null); + // Ensure arbitrary strings don't get stripped + assert.ok(outputChunkCode.match(/\/\/#\ssourceMappingURL=/)); + // Ensure the sourcemap comment has been removed + assert.is(outputChunkCode.match(/^\/\/#\ssourceMappingURL=.*\.map$/m), null); const outputAsset = path.join( outDir, outDirAssets.find((f) => /^worker-.*\.js$/.test(f)), ); const outputAssetSource = await fs.readFile(outputAsset, 'utf-8'); - assert.is(outputAssetSource.match(/\/\/#\ssourceMappingURL=(.*)/), null); + assert.is(outputAssetSource.match(/^\/\/#\ssourceMappingURL=.*\.map$/m), null); }); test('Should preserve sourcemaps if user has enabled them', async () => { @@ -64,7 +67,7 @@ test('Should preserve sourcemaps if user has enabled them', async () => { const outputJs = await fs.readFile(path.join(outDir, outputJsFileName), 'utf-8'); assert.match(outputJs, '//# sourceMappingURL='); - const outputMap = outputJs.match(/\/\/#\ssourceMappingURL=(.*)/)[1]; + const outputMap = outputJs.match(/^\/\/#\ssourceMappingURL=(.*)\.map$/m)[1]; assert.ok(outDirAssets.includes(outputMap)); });