-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathreact-app-rewire-js-ts.js
123 lines (106 loc) · 2.79 KB
/
react-app-rewire-js-ts.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
const path = require('path');
const tsLoaderMatcher = function(rule) {
return rule.test && rule.test.toString() === /\.(ts|tsx)$/.toString();
};
const jsLoaderMatcher = function(rule) {
return (
rule.loader &&
rule.loader.indexOf(`${path.sep}babel-loader${path.sep}`) !== -1
);
};
const getLoader = function(rules, matcher) {
let loader;
rules.some(rule => {
return (loader = matcher(rule)
? rule
: getLoader(rule.use || rule.oneOf || [], matcher));
});
return loader;
};
const getTsLoader = function(rules) {
return getLoader(rules, tsLoaderMatcher);
};
const getJsLoader = function(rules) {
return getLoader(rules, jsLoaderMatcher);
};
function tsConfig(config, env, babelPlugins) {
const tsLoader = getTsLoader(config.module.rules);
if (!tsLoader) {
console.log('ts-loader not found');
return config;
}
delete tsLoader.loader;
delete tsLoader.options;
// Replace loader with array of loaders with use: []
tsLoader.use = [
{
loader: require.resolve('babel-loader'),
options: {
cacheDirectory: true,
babelrc: false,
compact: true,
presets:
env === 'production'
? [require.resolve('babel-preset-react-app')]
: [],
plugins:
env === 'production'
? [...babelPlugins]
: [require.resolve('react-hot-loader/babel'), ...babelPlugins],
},
},
{
loader: require.resolve('ts-loader'),
options: {
transpileOnly: true,
configFile:
env === 'production' ? 'tsconfig.json' : 'tsconfig.dev.json',
},
},
];
}
function jsConfig(config, env, babelPlugins) {
const jsLoader = getJsLoader(config.module.rules);
if (!jsLoader) {
console.log('js-loader not found');
return config;
}
delete jsLoader.loader;
delete jsLoader.options;
if (env === 'production') {
jsLoader.include = [/node_modules/];
}
// Replace loader with array of loaders with use: []
jsLoader.use = [
{
loader: require.resolve('babel-loader'),
options: {
cacheDirectory: true,
babelrc: false,
compact: true,
presets: [
[
require.resolve('babel-preset-env'),
{
targets: {
browsers: ['>= 1%', 'chrome >= 45', 'Explorer 11'],
},
},
],
require.resolve('babel-preset-react-app'),
],
plugins:
env === 'production'
? [...babelPlugins]
: [require.resolve('react-hot-loader/babel'), ...babelPlugins],
},
},
];
}
module.exports = (config, env, babelPlugins = []) => {
// Typescript
tsConfig(config, env, babelPlugins);
// JavaScript
jsConfig(config, env, babelPlugins);
return config;
};