Skip to content

Commit

Permalink
Emit @babel/cli source maps based on configuration files (#14950)
Browse files Browse the repository at this point in the history
  • Loading branch information
liuxingbaoyu committed Sep 21, 2022
1 parent bedfc72 commit 40a6d42
Show file tree
Hide file tree
Showing 85 changed files with 301 additions and 41 deletions.
26 changes: 16 additions & 10 deletions packages/babel-cli/src/babel/dir.ts
Expand Up @@ -49,16 +49,22 @@ export default async function ({

if (!res) return FILE_TYPE.IGNORED;

// we've requested explicit sourcemaps to be written to disk
if (
res.map &&
babelOptions.sourceMaps &&
babelOptions.sourceMaps !== "inline"
) {
const mapLoc = dest + ".map";
res.code = util.addSourceMappingUrl(res.code, mapLoc);
res.map.file = path.basename(relative);
outputFileSync(mapLoc, JSON.stringify(res.map));
if (res.map) {
let outputMap: "both" | "external" | false = false;
if (babelOptions.sourceMaps && babelOptions.sourceMaps !== "inline") {
outputMap = "external";
} else if (babelOptions.sourceMaps == undefined) {
outputMap = util.hasDataSourcemap(res.code) ? "external" : "both";
}

if (outputMap) {
const mapLoc = dest + ".map";
if (outputMap === "external") {
res.code = util.addSourceMappingUrl(res.code, mapLoc);
}
res.map.file = path.basename(relative);
outputFileSync(mapLoc, JSON.stringify(res.map));
}
}

outputFileSync(dest, res.code);
Expand Down
42 changes: 27 additions & 15 deletions packages/babel-cli/src/babel/file.ts
Expand Up @@ -12,30 +12,40 @@ import type {
SectionedSourceMap,
SourceMapInput,
TraceMap,
DecodedSourceMap,
} from "@jridgewell/trace-mapping";
import type { FileResult } from "@babel/core";

type CompilationOutput = {
code: string;
map: SourceMapInput;
hasRawMap: boolean;
};

export default async function ({
cliOptions,
babelOptions,
}: CmdOptions): Promise<void> {
function buildResult(fileResults: Array<any>): CompilationOutput {
function buildResult(fileResults: Array<FileResult>): CompilationOutput {
const mapSections: SectionedSourceMap["sections"] = [];

let code = "";
let offset = 0;

let hasRawMap = false;

for (const result of fileResults) {
if (!result) continue;

hasRawMap = !!result.map;

mapSections.push({
offset: { line: offset, column: 0 },
map: result.map || emptyMap(),
map: result.map || {
version: 3,
names: [],
sources: [],
mappings: [],
},
});

code += result.code + "\n";
Expand All @@ -51,7 +61,7 @@ export default async function ({
sections: mapSections,
});
// For some reason, the spec doesn't allow sourceRoot when constructing a
// sectioned sorucemap. But AllMap returns a regular sourcemap, we can
// sectioned sourcemap. But AllMap returns a regular sourcemap, we can
// freely add to with a sourceRoot.
map.sourceRoot = babelOptions.sourceRoot;

Expand All @@ -67,8 +77,10 @@ export default async function ({
return {
map: map,
code: code,
hasRawMap: hasRawMap,
};
}

function countNewlines(code: string): number {
let count = 0;
let index = -1;
Expand All @@ -77,25 +89,25 @@ export default async function ({
}
return count;
}
function emptyMap(): DecodedSourceMap {
return {
version: 3,
names: [],
sources: [],
mappings: [],
};
}

function output(fileResults: Array<string>): void {
function output(fileResults: Array<FileResult>): void {
const result = buildResult(fileResults);

if (cliOptions.outFile) {
fs.mkdirSync(path.dirname(cliOptions.outFile), { recursive: true });

// we've requested for a sourcemap to be written to disk
let outputMap: "both" | "external" | false = false;
if (babelOptions.sourceMaps && babelOptions.sourceMaps !== "inline") {
outputMap = "external";
} else if (babelOptions.sourceMaps == undefined && result.hasRawMap) {
outputMap = util.hasDataSourcemap(result.code) ? "external" : "both";
}

if (outputMap) {
const mapLoc = cliOptions.outFile + ".map";
result.code = util.addSourceMappingUrl(result.code, mapLoc);
if (outputMap === "external") {
result.code = util.addSourceMappingUrl(result.code, mapLoc);
}
fs.writeFileSync(
mapLoc,
JSON.stringify(encodedMap(result.map as TraceMap)),
Expand Down
9 changes: 8 additions & 1 deletion packages/babel-cli/src/babel/options.ts
Expand Up @@ -84,7 +84,12 @@ commander.option(
);

// General source map formatting.
commander.option("-s, --source-maps [true|false|inline|both]", "", booleanify);
commander.option(
"-s, --source-maps [true|false|inline|both]",
"",
booleanify,
undefined,
);
commander.option(
"--source-map-target [string]",
"Set `file` on returned source map.",
Expand Down Expand Up @@ -355,6 +360,8 @@ export default function parseArgv(args: Array<string>): CmdOptions | null {
}

function booleanify(val: any): boolean | any {
if (val === undefined) return undefined;

if (val === "true" || val == 1) {
return true;
}
Expand Down
22 changes: 11 additions & 11 deletions packages/babel-cli/src/babel/util.ts
Expand Up @@ -5,6 +5,8 @@ import fs from "fs";

import * as watcher from "./watcher";

import type { FileResult, InputOptions } from "@babel/core";

export function chmod(src: string, dest: string): void {
try {
fs.chmodSync(dest, fs.statSync(src).mode);
Expand Down Expand Up @@ -57,40 +59,38 @@ export function addSourceMappingUrl(code: string, loc: string): string {
return code + "\n//# sourceMappingURL=" + path.basename(loc);
}

export function hasDataSourcemap(code: string): boolean {
const pos = code.lastIndexOf("\n", code.length - 2);
return pos != -1 && code.lastIndexOf("//# sourceMappingURL") < pos;
}

const CALLER = {
name: "@babel/cli",
};

export function transformRepl(
filename: string,
code: string,
opts: any,
): Promise<any> {
export function transformRepl(filename: string, code: string, opts: any) {
opts = {
...opts,
caller: CALLER,
filename,
};

return new Promise((resolve, reject) => {
return new Promise<FileResult>((resolve, reject) => {
babel.transform(code, opts, (err, result) => {
if (err) reject(err);
else resolve(result);
});
});
}

export async function compile(
filename: string,
opts: any | Function,
): Promise<any> {
export async function compile(filename: string, opts: InputOptions) {
opts = {
...opts,
caller: CALLER,
};

// TODO (Babel 8): Use `babel.transformFileAsync`
const result: any = await new Promise((resolve, reject) => {
const result = await new Promise<FileResult>((resolve, reject) => {
babel.transformFile(filename, opts, (err, result) => {
if (err) reject(err);
else resolve(result);
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

@@ -0,0 +1,3 @@
{
"sourceMaps": "both"
}
@@ -0,0 +1,3 @@
{
"sourceMaps": false
}
@@ -0,0 +1 @@
(() => 42)
@@ -0,0 +1 @@
arr.map(x => x * MULTIPLIER);
@@ -0,0 +1,3 @@
{
"args": ["src", "--out-dir", "lib", "--verbose"]
}
@@ -0,0 +1,5 @@
"use strict";

(function () {
return 42;
});
@@ -0,0 +1,5 @@
"use strict";

arr.map(function (x) {
return x * MULTIPLIER;
});
@@ -0,0 +1,3 @@
src/bar/bar.js -> lib/bar/bar.js
src/foo.js -> lib/foo.js
Successfully compiled 2 files with Babel (123ms).
@@ -0,0 +1,3 @@
{
"sourceMaps": "inline"
}
@@ -0,0 +1 @@
(() => 42)
@@ -0,0 +1 @@
arr.map(x => x * MULTIPLIER);
@@ -0,0 +1,3 @@
{
"args": ["src", "--out-dir", "lib", "--verbose"]
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

@@ -0,0 +1,3 @@
src/bar/bar.js -> lib/bar/bar.js
src/foo.js -> lib/foo.js
Successfully compiled 2 files with Babel (123ms).
@@ -0,0 +1,3 @@
{
"sourceMaps": true
}
@@ -0,0 +1 @@
(() => 42)
@@ -0,0 +1 @@
arr.map(x => x * MULTIPLIER);
@@ -0,0 +1,3 @@
{
"args": ["src", "--out-dir", "lib", "--verbose"]
}
@@ -0,0 +1,5 @@
"use strict";

(function () {
return 42;
});

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

@@ -0,0 +1,5 @@
"use strict";

arr.map(function (x) {
return x * MULTIPLIER;
});

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

@@ -0,0 +1,3 @@
src/bar/bar.js -> lib/bar/bar.js
src/foo.js -> lib/foo.js
Successfully compiled 2 files with Babel (123ms).
@@ -0,0 +1 @@
(() => 42)
@@ -0,0 +1 @@
arr.map(x => x * MULTIPLIER);
@@ -0,0 +1,3 @@
{
"args": ["src", "--out-dir", "lib", "--verbose"]
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

@@ -0,0 +1,3 @@
src/bar/bar.js -> lib/bar/bar.js
src/foo.js -> lib/foo.js
Successfully compiled 2 files with Babel (123ms).
@@ -0,0 +1,3 @@
{
"sourceMaps": false
}
@@ -0,0 +1 @@
(() => 42)
@@ -0,0 +1 @@
arr.map(x => x * MULTIPLIER);
@@ -0,0 +1,3 @@
{
"args": ["src", "--out-dir", "lib", "--verbose"]
}
@@ -0,0 +1,5 @@
"use strict";

(function () {
return 42;
});
@@ -0,0 +1,5 @@
"use strict";

arr.map(function (x) {
return x * MULTIPLIER;
});
@@ -0,0 +1,3 @@
src/bar/bar.js -> lib/bar/bar.js
src/foo.js -> lib/foo.js
Successfully compiled 2 files with Babel (123ms).
@@ -0,0 +1,3 @@
{
"sourceMaps": "both"
}

0 comments on commit 40a6d42

Please sign in to comment.