-
Notifications
You must be signed in to change notification settings - Fork 43
/
plugin.js
276 lines (243 loc) · 7.48 KB
/
plugin.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import { resolve, dirname, relative } from 'path';
import { ResolverFactory, SyncNodeJsInputFileSystem } from 'enhanced-resolve';
import { parse } from 'babylon';
import template from 'lodash/template';
import traverse from 'babel-traverse';
import runWebPackSync from './runWebPackSync';
import memoize from './memoize';
import { StringLiteral } from 'babel-types';
import colors from 'colors/safe';
const processWebPackResult = (webPackResult, { output: { publicPath = '' } = {} } = {}) => {
const webpackResultAst = parse(webPackResult);
let expr = null;
// without ExtractTextPlugin css-loader result looks like `blabla.locals = {...blbala}`
traverse(webpackResultAst, {
FunctionExpression(pathFn) {
if (pathFn.node.params.length >= 2 && pathFn.node.params[1].name === 'exports') {
pathFn.traverse({
AssignmentExpression(path) {
if (path.node.left.property && path.node.left.property.name === 'locals') {
expr = path.node.right;
}
},
});
}
},
});
// with ExtractTextPlugin css-loader result looks like `module.exports = {...blbala}`
if (expr === null) {
traverse(webpackResultAst, {
FunctionExpression(pathFn) {
if (pathFn.node.params.length >= 2 && pathFn.node.params[1].name === 'exports') {
pathFn.traverse({
AssignmentExpression(path) {
if (path.node.left.property && path.node.left.property.name === 'exports') {
expr = path.node.right;
}
},
BinaryExpression(pathBin) {
pathBin.traverse({
MemberExpression(pathM) {
if (
pathM.node.object.name === '__webpack_require__' &&
pathM.node.property.name === 'p'
) {
pathM.replaceWith(StringLiteral(publicPath)); // eslint-disable-line
}
},
});
},
});
}
},
});
}
return traverse.removeProperties(expr);
};
// memoize resolver instance
const getEnhancedResolver = memoize(
({ resolve: configResolve }) => (
ResolverFactory.createResolver({
fileSystem: new SyncNodeJsInputFileSystem(),
...configResolve,
// enhanced-resolve does not support modulesDirectories, lets add 2 modules
...(
configResolve && (configResolve.modules || configResolve.modulesDirectories) &&
{
modules: [
...(configResolve.modules || []),
...(configResolve.modulesDirectories || []),
],
}
),
})
)
);
const localInteropRequire = (path) => {
const res = require(resolve(process.cwd(), path));
if ('default' in res) {
return res.default;
}
return res;
};
// https://github.com/webpack/node-libs-browser
const internalNodeModules = {
assert: 1,
buffer: 1,
child_process: 1,
cluster: 1,
console: 1,
constants: 1,
crypto: 1,
dgram: 1,
dns: 1,
domain: 1,
events: 1,
fs: 1,
http: 1,
https: 1,
module: 1,
net: 1,
os: 1,
path: 1,
process: 1,
punycode: 1,
querystring: 1,
readline: 1,
repl: 1,
stream: 1,
string_decoder: 1,
sys: 1,
timers: 1,
tls: 1,
tty: 1,
url: 1,
util: 1,
vm: 1,
zlib: 1,
};
const resolveFilePath = (resolver, filenameAbs, filePath) => {
try {
return resolver.resolveSync({}, dirname(filenameAbs), filePath);
} catch (e) {
if (!(filePath in internalNodeModules)) {
throw e;
}
}
return undefined;
};
const isInAbsResolveModulesPath = memoize(
({ resolve: { modules = [], modulesDirectories = [] } = {} }) => {
// support only absolute pathes in resolve.modules for js and jsx files
// because node_modules aliasing is a bad practice
const absPathes = [...modules, ...modulesDirectories]
.filter(p => p === resolve(p));
return (fileAbsPath) => absPathes.some((p) => fileAbsPath.indexOf(p) === 0);
}
);
const isJSFile = (fileAbsPath) => {
const test = /\.jsx?$/;
return test.test(fileAbsPath);
};
const isRelativePath = (fileAbsPath) => fileAbsPath.indexOf('.') === 0;
const warn = (() => {
const msgs = {};
return (message) => {
if (message in msgs) {
return;
}
msgs[message] = true;
console.error( // eslint-disable-line
colors.yellow(message)
);
};
})();
export default function ({ types: t }) {
return {
visitor: {
CallExpression(
path,
{
file: { opts: { filenameRelative } },
opts: { config: configPath = './webpack.config.js', verbose = true } = {},
}
) {
// don't process current plugin
if (typeof getEnhancedResolver === 'undefined') {
return;
}
const { callee: { name: calleeName }, arguments: args } = path.node;
if (calleeName !== 'require' || !args.length || !t.isStringLiteral(args[0])) {
return;
}
// support env var interpolation into configPath
const compiledConfigPath = template(configPath)(process.env);
const config = compiledConfigPath === configPath
? localInteropRequire(resolve(process.cwd(), compiledConfigPath))
: localInteropRequire(resolve(compiledConfigPath));
if (Object.keys(config).length === 0) {
// it's possible require calls inside webpack config or bad config
return;
}
if (process.env.BABEL_DISABLE_CACHE !== '1') {
warn(
`babel-plugin-webpack-loader:
To avoid caching errors you need to set BABEL_DISABLE_CACHE=1 environment variable.
More information at issue #36`
);
}
const [{ value: filePath }] = args;
// to support babel builds (babel-node works fine)
const filenameAbs = resolve(filenameRelative);
const resolver = getEnhancedResolver(config);
const fileAbsPath = resolveFilePath(resolver, filenameAbs, filePath);
if (!fileAbsPath) {
return;
}
// for js and jsx files inside resolve.modules,
// for absolute folders only i.e. `path.join(__dirname, 'resolveDir')`
// replace require('xxx') to relative path i.e. `require('../resolveDir/xxx')`
if (
isJSFile(fileAbsPath) &&
!isRelativePath(filePath) &&
isInAbsResolveModulesPath(config)(fileAbsPath)
) {
const relPath = (
(p) => isRelativePath(p)
? p
: `./${p}`
)(relative(dirname(filenameAbs), fileAbsPath));
// path.replaceWith(t.stringLiteral(relPath));
path.get('arguments.0').replaceWith(t.stringLiteral(relPath));
return;
}
if (config.module.loaders.some((l) => l.test.test(filePath) || l.test.test(fileAbsPath))) {
if (isJSFile(fileAbsPath)) {
warn(
`babel-plugin-webpack-loader:
js and jsx files in loaders is unsupported by webpack-loader plugin.
all babel settings in loader will be skipped`
);
return;
}
const webPackResult = runWebPackSync({
path: fileAbsPath,
configPath: compiledConfigPath,
config,
verbose,
});
const expr = processWebPackResult(webPackResult, config);
if (expr !== null) {
if (expr.type === 'FunctionExpression') {
path.remove();
} else {
path.replaceWith(expr);
}
} else {
path.remove();
}
}
},
},
};
}