forked from laurent22/joplin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buildInjectedJs.ts
209 lines (178 loc) · 5.54 KB
/
buildInjectedJs.ts
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
// React Native WebView cannot load external JS files, however it can load
// arbitrary JS via the injectedJavaScript property. So we use this to load external
// files: First here we convert the JS file to a plain string, and that string
// is then loaded by eg. the Mermaid plugin, and finally injected in the WebView.
import { mkdirp, readFile, writeFile } from 'fs-extra';
import { dirname, extname, basename } from 'path';
const execa = require('execa');
import webpack from 'webpack';
const rootDir = dirname(dirname(dirname(__dirname)));
const mobileDir = `${rootDir}/packages/app-mobile`;
const outputDir = `${mobileDir}/lib/rnInjectedJs`;
// Stores the contents of the file at [filePath] as an importable string.
// [name] should be the name (excluding the .js extension) of the output file that will contain
// the JSON-ified file content.
async function copyJs(name: string, filePath: string) {
const outputPath = `${outputDir}/${name}.js`;
console.info(`Creating: ${outputPath}`);
const js = await readFile(filePath, 'utf-8');
const json = `module.exports = ${JSON.stringify(js)};`;
await writeFile(outputPath, json);
}
class BundledFile {
private readonly bundleOutputPath: string;
private readonly bundleMinifiedPath: string;
private readonly bundleBaseName: string;
private readonly rootFileDirectory: string;
public constructor(
public readonly bundleName: string,
private readonly sourceFilePath: string
) {
this.rootFileDirectory = dirname(sourceFilePath);
this.bundleBaseName = basename(sourceFilePath, extname(sourceFilePath));
this.bundleOutputPath = `${this.rootFileDirectory}/${this.bundleBaseName}.bundle.js`;
this.bundleMinifiedPath = `${this.rootFileDirectory}/${this.bundleBaseName}.bundle.min.js`;
}
private getWebpackOptions(mode: 'production' | 'development'): webpack.Configuration {
const config: webpack.Configuration = {
mode,
entry: this.sourceFilePath,
output: {
path: this.rootFileDirectory,
filename: `${this.bundleBaseName}.bundle.js`,
library: {
type: 'window',
name: this.bundleName,
},
},
// See https://webpack.js.org/guides/typescript/
module: {
rules: [
{
// Include .tsx to include react components
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
// Increase the minimum size required
// to trigger warnings.
// See https://stackoverflow.com/a/53517149/17055750
performance: {
maxAssetSize: 2_000_000, // 2-ish MiB
maxEntrypointSize: 2_000_000,
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
};
return config;
}
private async uglify() {
console.info(`Minifying bundle: ${this.bundleName}...`);
await execa('yarn', [
'run', 'uglifyjs',
'--compress',
'-o', this.bundleMinifiedPath,
this.bundleOutputPath,
]);
}
private handleErrors(err: Error | undefined | null, stats: webpack.Stats | undefined): boolean {
let failed = false;
if (err) {
console.error(`Error: ${err.name}`, err.message, err.stack);
failed = true;
} else if (stats?.hasErrors() || stats?.hasWarnings()) {
const data = stats.toJson();
if (data.warnings && data.warningsCount) {
console.warn('Warnings: ', data.warningsCount);
for (const warning of data.warnings) {
// Stack contains the message
if (warning.stack) {
console.warn(warning.stack);
} else {
console.warn(warning.message);
}
}
}
if (data.errors && data.errorsCount) {
console.error('Errors: ', data.errorsCount);
for (const error of data.errors) {
if (error.stack) {
console.error(error.stack);
} else {
console.error(error.message);
}
console.error();
}
failed = true;
}
}
return failed;
}
// Create a minified JS file in the same directory as `this.sourceFilePath` with
// the same name.
public build() {
const compiler = webpack(this.getWebpackOptions('production'));
return new Promise<void>((resolve, reject) => {
console.info(`Building bundle: ${this.bundleName}...`);
compiler.run((err, stats) => {
let failed = this.handleErrors(err, stats);
// Clean up.
compiler.close(async (error) => {
if (error) {
console.error('Error cleaning up:', error);
failed = true;
}
if (!failed) {
await this.uglify();
resolve();
} else {
reject();
}
});
});
});
}
public startWatching() {
const compiler = webpack(this.getWebpackOptions('development'));
const watchOptions = {
ignored: '**/node_modules',
};
console.info('Watching bundle: ', this.bundleName);
compiler.watch(watchOptions, async (err, stats) => {
const failed = this.handleErrors(err, stats);
if (!failed) {
await this.uglify();
await this.copyToImportableFile();
}
});
}
// Creates a file that can be imported by React native. This file contains the
// bundled JS as a string.
public async copyToImportableFile() {
await copyJs(`${this.bundleBaseName}.bundle`, this.bundleMinifiedPath);
}
}
const bundledFiles: BundledFile[] = [
new BundledFile(
'codeMirrorBundle',
`${mobileDir}/components/NoteEditor/CodeMirror/CodeMirror.ts`
),
];
export async function buildInjectedJS() {
await mkdirp(outputDir);
// Build all in parallel
await Promise.all(bundledFiles.map(async file => {
await file.build();
await file.copyToImportableFile();
}));
await copyJs('webviewLib', `${mobileDir}/../lib/renderers/webviewLib.js`);
}
export async function watchInjectedJS() {
// Watch for changes
for (const file of bundledFiles) {
file.startWatching();
}
}