Skip to content

Commit

Permalink
Add source map support to the inline-require optimizer (#9511)
Browse files Browse the repository at this point in the history
  • Loading branch information
mattcompiles committed Jan 30, 2024
1 parent 86922d7 commit 120103a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
1 change: 1 addition & 0 deletions packages/optimizers/inline-requires/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
},
"dependencies": {
"@parcel/plugin": "2.11.0",
"@parcel/source-map": "^2.1.1",
"@parcel/types": "2.11.0",
"@swc/core": "^1.3.36",
"nullthrows": "^1.1.1"
Expand Down
33 changes: 28 additions & 5 deletions packages/optimizers/inline-requires/src/InlineRequires.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {parse, print} from '@swc/core';
import {RequireInliningVisitor} from './RequireInliningVisitor';
import type {SideEffectsMap} from './types';
import nullthrows from 'nullthrows';
import SourceMap from '@parcel/source-map';

let publicIdToAssetSideEffects = null;

Expand Down Expand Up @@ -46,9 +47,17 @@ module.exports = new Optimizer<empty, BundleConfig>({
return {publicIdToAssetSideEffects};
},

async optimize({bundle, contents, map, tracer, logger, bundleConfig}) {
async optimize({
bundle,
contents,
map: originalMap,
tracer,
logger,
bundleConfig,
options,
}) {
if (!bundle.env.shouldOptimize) {
return {contents, map};
return {contents, map: originalMap};
}

try {
Expand All @@ -66,9 +75,23 @@ module.exports = new Optimizer<empty, BundleConfig>({
publicIdToAssetSideEffects: bundleConfig.publicIdToAssetSideEffects,
});
visitor.visitProgram(ast);

if (visitor.dirty) {
const newContents = await print(ast, {});
return {contents: newContents.code, map};
const result = await print(ast, {sourceMaps: !!bundle.env.sourceMap});

let sourceMap = null;
let resultMap = result.map;
let contents: string = nullthrows(result.code);

if (resultMap != null) {
sourceMap = new SourceMap(options.projectRoot);
sourceMap.addVLQMap(JSON.parse(resultMap));
if (originalMap) {
sourceMap.extends(originalMap);
}
}

return {contents, map: sourceMap};
}
} catch (err) {
logger.error({
Expand All @@ -77,6 +100,6 @@ module.exports = new Optimizer<empty, BundleConfig>({
stack: err.stack,
});
}
return {contents, map};
return {contents, map: originalMap};
},
});

0 comments on commit 120103a

Please sign in to comment.