forked from aws-amplify/amplify-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.js
238 lines (209 loc) · 6.54 KB
/
build.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
'use strict';
const path = require('path');
const utility = require('./utility');
const ts = require('typescript');
const externals = require('./rollup-externals');
const winston = require('winston');
const logger = winston.createLogger({
level: process.env.LOG_LEVEL ? process.env.LOG_LEVEL.toLowerCase() : 'info',
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.prettyPrint(2),
winston.format.colorize({ all: true })
),
}),
],
});
// path of root
const rootPath = path.resolve(__dirname, '../');
// path of each package
const pkgRootPath = process.cwd();
const pkgTscES5OutDir = path.join(pkgRootPath, 'lib');
const pkgTscES6OutDir = path.join(pkgRootPath, 'lib-esm');
const pkgSrcDir = path.join(pkgRootPath, 'src');
const typeRoots = [rootPath, pkgRootPath].map(basePath =>
path.join(basePath, 'node_modules/@types')
);
const packageJsonPath = path.join(pkgRootPath, 'package');
const packageInfo = require(packageJsonPath);
const pkgRollUpInputFile = path.join(pkgTscES5OutDir, 'index.js');
const pkgRollUpOutputFile = path.join(pkgRootPath, packageInfo.main);
const es5TsBuildInfoFilePath = path.join(pkgTscES5OutDir, '.tsbuildinfo');
const es6TsBuildInfoFilePath = path.join(pkgTscES6OutDir, '.tsbuildinfo');
async function buildRollUp() {
logger.info(`Building Roll up bundle file under ${pkgRootPath}`);
const rollup = require('rollup');
const resolve = require('rollup-plugin-node-resolve');
const sourceMaps = require('rollup-plugin-sourcemaps');
const json = require('rollup-plugin-json');
// For more info see: https://github.com/rollup/rollup/issues/1518#issuecomment-321875784
const onwarn = warning => {
if (warning.code === 'THIS_IS_UNDEFINED') {
return;
}
console.warn(warning.message);
};
const inputOptions = {
pkgRollUpInputFile,
plugins: [json(), resolve({ extensions: ['.js', '.json'] }), sourceMaps()],
external: externals[packageInfo.name],
onwarn,
};
const outputOptions = {
pkgRollUpOutputFile,
format: 'cjs',
name: 'index',
sourcemap: true,
exports: 'named',
};
logger.info(`Using the rollup configuration:`);
logger.info(inputOptions);
logger.info(outputOptions);
try {
const bundle = await rollup.rollup(inputOptions);
await bundle.write(outputOptions);
} catch (e) {
logger.error(e);
}
}
const formatHost = {
getCanonicalFileName: path => path,
getCurrentDirectory: ts.sys.getCurrentDirectory,
getNewLine: () => ts.sys.newLine,
};
function runTypeScriptWithoutWatchMode(fileNames, options) {
let program = ts.createProgram(fileNames, options);
let emitResult = program.emit();
let allDiagnostics = ts
.getPreEmitDiagnostics(program)
.concat(emitResult.diagnostics);
allDiagnostics.forEach(diagnostic => {
reportErrorDiagnostic(diagnostic);
});
let exitCode = emitResult.emitSkipped ? 1 : 0;
logger.info(`Process exiting with code '${exitCode}'.`);
process.exit(exitCode);
}
function runTypeScriptWithWatchMode(fileNames, options) {
// https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#writing-an-incremental-program-watcher
const createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram;
const host = ts.createWatchCompilerHost(
fileNames,
options,
ts.sys,
createProgram,
reportErrorDiagnostic,
reportWatchStatusChanged,
null
);
// `createWatchProgram` creates an initial program, watches files, and updates
// the program over time.
ts.createWatchProgram(host);
}
function reportErrorDiagnostic(diagnostic) {
if (diagnostic.file) {
let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(
diagnostic.start
);
let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
logger.error(
`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`
);
} else {
logger.error(
`${ts.flattenDiagnosticMessageText(
diagnostic.messageText,
formatHost.getNewLine()
)}`
);
}
}
/**
* Prints a diagnostic every time the watch status changes.
* This is mainly for messages like "Starting compilation" or "Compilation completed".
*/
function reportWatchStatusChanged(diagnostic, newLine, options, errorCount) {
logger.info(ts.formatDiagnostic(diagnostic, formatHost));
}
async function buildES5(typeScriptCompiler) {
const jsx = packageInfo.name === 'aws-amplify-react' ? 'react' : undefined;
// tsconfig for ES5 generating
let compilerOptions = {
noImplicitAny: false,
lib: ['dom', 'es2017', 'esnext.asynciterable'],
jsx: jsx,
sourceMap: true,
target: 'es5',
module: 'commonjs',
moduleResolution: 'node',
declaration: true,
noEmitOnError: true,
incremental: true,
tsBuildInfoFile: es5TsBuildInfoFilePath,
typeRoots,
// temporary fix
types: ['node'],
outDir: pkgTscES5OutDir,
};
compilerOptions = ts.convertCompilerOptionsFromJson(compilerOptions);
const include = [pkgSrcDir];
logger.debug(`Using the typescript compiler options:`);
logger.debug(compilerOptions);
let fileList = [];
Promise.all(
include.map(async source => {
const list = await utility.iterateFiles(source);
return (fileList = fileList.concat(list));
})
).then(() => {
logger.debug('Files to be transpiled by tsc:');
logger.debug(fileList);
typeScriptCompiler(fileList, compilerOptions.options);
});
}
function buildES6(typeScriptCompiler) {
const jsx = packageInfo.name === 'aws-amplify-react' ? 'react' : undefined;
// tsconfig for ESM generating
let compilerOptions = {
noImplicitAny: false,
lib: ['dom', 'es2017', 'esnext.asynciterable'],
jsx: jsx,
sourceMap: true,
target: 'es5',
module: 'es2015',
moduleResolution: 'node',
declaration: true,
noEmitOnError: true,
incremental: true,
tsBuildInfoFile: es6TsBuildInfoFilePath,
typeRoots,
// temporary fix
types: ['node'],
outDir: pkgTscES6OutDir,
};
compilerOptions = ts.convertCompilerOptionsFromJson(compilerOptions);
const include = [pkgSrcDir];
logger.debug(`Using the typescript compiler options:`);
logger.debug(compilerOptions);
let fileList = [];
Promise.all(
include.map(async source => {
const list = await utility.iterateFiles(source);
return (fileList = fileList.concat(list));
})
).then(() => {
logger.debug('Files to be transpiled by tsc:');
logger.debug(fileList);
typeScriptCompiler(fileList, compilerOptions.options);
});
}
function build(type, watchMode) {
if (type === 'rollup') buildRollUp();
var typeScriptCompiler = watchMode
? runTypeScriptWithWatchMode
: runTypeScriptWithoutWatchMode;
if (type === 'es5') buildES5(typeScriptCompiler);
if (type === 'es6') buildES6(typeScriptCompiler);
}
module.exports = build;