/
transform-file.js
95 lines (81 loc) 路 2.22 KB
/
transform-file.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// @flow
import fs from "fs";
import loadConfig, { type InputOptions } from "./config";
import {
runSync,
runAsync,
type FileResult,
type FileResultCallback,
} from "./transformation";
import typeof * as transformFileBrowserType from "./transform-file-browser";
import typeof * as transformFileType from "./transform-file";
// Kind of gross, but essentially asserting that the exports of this module are the same as the
// exports of transform-file-browser, since this file may be replaced at bundle time with
// transform-file-browser.
((({}: any): $Exact<transformFileBrowserType>): $Exact<transformFileType>);
type TransformFile = {
(filename: string, callback: FileResultCallback): void,
(filename: string, opts: ?InputOptions, callback: FileResultCallback): void,
};
export const transformFile: TransformFile = (function transformFile(
filename,
opts,
callback,
) {
let options;
if (typeof opts === "function") {
callback = opts;
opts = undefined;
}
if (opts == null) {
options = { filename };
} else if (opts && typeof opts === "object") {
options = {
...opts,
filename,
};
}
process.nextTick(() => {
let cfg;
try {
cfg = loadConfig(options);
if (cfg === null) return callback(null, null);
} catch (err) {
return callback(err);
}
// Reassignment to keep Flow happy.
const config = cfg;
fs.readFile(filename, "utf8", function(err, code: string) {
if (err) return callback(err, null);
runAsync(config, code, null, callback);
});
});
}: Function);
export function transformFileSync(
filename: string,
opts: ?InputOptions,
): FileResult | null {
let options;
if (opts == null) {
options = { filename };
} else if (opts && typeof opts === "object") {
options = {
...opts,
filename,
};
}
const config = loadConfig(options);
if (config === null) return null;
return runSync(config, fs.readFileSync(filename, "utf8"));
}
export function transformFileAsync(
filename: string,
opts: ?InputOptions,
): Promise<FileResult | null> {
return new Promise((res, rej) => {
transformFile(filename, opts, (err, result) => {
if (err == null) res(result);
else rej(err);
});
});
}