forked from uber/baseweb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vite.config.mjs
118 lines (112 loc) · 2.85 KB
/
vite.config.mjs
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
/*
Copyright (c) Uber Technologies, Inc.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
*/
//@noflow
import flowRemoveTypes from 'flow-remove-types';
import { createFilter } from 'rollup-pluginutils';
import { readFile } from 'fs';
const EXPORT_TYPES = /export\stype\s\*\sfrom\s[a-zA-Z0-9."/\-_']+;/gm;
/**
* Create a Vite plugin object
* @returns {import('vite').Plugin} Returns esbuild plugin object
*/
function flowPlugin(
options /** {import('../shared/types').VitePluginOptions */ = {
include: /\.(flow|jsx?)$/,
exclude: /node_modules/,
flow: {
all: false,
pretty: false,
ignoreUninitializedFields: false,
},
}
) {
const filter = createFilter(options.include, options.exclude);
return {
enforce: 'pre',
name: 'flow',
transform(src, id) {
// eslint-disable-line consistent-return
if (filter(id)) {
const transformed = flowRemoveTypes(src, options.flow);
return {
code: transformed.toString().replace(EXPORT_TYPES, ''),
map: null,
};
}
return undefined;
},
};
}
function esbuildFlowPlugin(
filter = /\.(flow|jsx?)$/,
flowOptions = {
all: false,
pretty: false,
ignoreUninitializedFields: false,
}
) {
return {
name: 'flow',
// @ts-ignore
setup(build) {
// @ts-ignore
build.onLoad({ filter }, async ({ path, namespace }) => {
try {
const src = await new Promise((resolve, reject) => {
readFile(path, (error, data) => {
if (error) {
reject(error);
} else {
resolve(data.toString('utf-8'));
}
});
});
const transformed = flowRemoveTypes(src, flowOptions);
return {
contents: transformed.toString().replace(EXPORT_TYPES, ''),
loader: src.includes('@flow\n') ? 'jsx' : 'js',
};
} catch (error) {
return {
errors: [
{
// @ts-ignore
text: error.message,
location: {
file: path,
namespace,
},
detail: error,
},
],
};
}
});
},
};
}
const viteConfig = async ({ mode }) => ({
// when built in CI, change the base URL so baseweb.design/ladle works
// eslint-disable-next-line cup/no-undef
base: process.env.CLOUDFLARE_BUILD ? '/ladle/' : '/',
plugins: [flowPlugin()],
define: {
__BROWSER__: true,
__NODE__: false,
__DEV__: mode === 'development',
},
optimizeDeps: {
esbuildOptions: {
plugins: [esbuildFlowPlugin()],
},
},
esbuild: {
include: /\.(tsx?|jsx?)$/,
exclude: [],
loader: 'tsx',
},
});
export default viteConfig;