UNPKG

11.1 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6
7var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
8
9var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
10
11exports.default = function (_ref4) {
12 var t = _ref4.types;
13
14 return {
15 visitor: {
16 CallExpression: function CallExpression(path, _ref5) {
17 var filenameRelative = _ref5.file.opts.filenameRelative;
18 var _ref5$opts = _ref5.opts;
19 _ref5$opts = _ref5$opts === undefined ? {} : _ref5$opts;
20 var _ref5$opts$config = _ref5$opts.config;
21 var configPath = _ref5$opts$config === undefined ? './webpack.config.js' : _ref5$opts$config;
22 var _ref5$opts$verbose = _ref5$opts.verbose;
23 var verbose = _ref5$opts$verbose === undefined ? true : _ref5$opts$verbose;
24 var _ref5$opts$skipJs = _ref5$opts.skipJs;
25 var skipJs = _ref5$opts$skipJs === undefined ? true : _ref5$opts$skipJs;
26
27 // don't process current plugin
28 if (typeof getEnhancedResolver === 'undefined') {
29 return;
30 }
31
32 var _path$node = path.node;
33 var calleeName = _path$node.callee.name;
34 var args = _path$node.arguments;
35
36
37 if (calleeName !== 'require' || !args.length || !t.isStringLiteral(args[0])) {
38 return;
39 }
40
41 // support env var interpolation into configPath
42 var compiledConfigPath = (0, _template2.default)(configPath)(process.env);
43 var config = compiledConfigPath === configPath ? localInteropRequire((0, _path.resolve)(process.cwd(), compiledConfigPath)) : localInteropRequire((0, _path.resolve)(compiledConfigPath));
44
45 if (typeof config === 'function') {
46 config = config();
47 }
48
49 if (Object.keys(config).length === 0) {
50 // it's possible require calls inside webpack config or bad config
51 return;
52 }
53
54 if (process.env.BABEL_DISABLE_CACHE !== '1') {
55 warn('babel-plugin-webpack-loader:\nTo avoid caching errors you need to set BABEL_DISABLE_CACHE=1 environment variable.\nMore information at issue #36');
56 }
57
58 var _args = _slicedToArray(args, 1);
59
60 var originalFilePath = _args[0].value;
61
62
63 var parts = originalFilePath.split('!');
64 var filePath = parts.pop();
65 var loaders = parts.join('!');
66
67 if (loaders) {
68 loaders += '!';
69 }
70
71 // to support babel builds (babel-node works fine)
72 var filenameAbs = (0, _path.resolve)(filenameRelative);
73
74 var resolver = getEnhancedResolver(config);
75
76 var fileAbsPath = resolveFilePath(resolver, filenameAbs, filePath);
77
78 if (!fileAbsPath) {
79 return;
80 }
81
82 // for js and jsx files inside resolve.modules,
83 // for absolute folders only i.e. `path.join(__dirname, 'resolveDir')`
84 // replace require('xxx') to relative path i.e. `require('../resolveDir/xxx')`
85 if (isJSFile(fileAbsPath) && !isRelativePath(filePath) && isInAbsResolveModulesPath(config)(fileAbsPath)) {
86 var relPath = function (p) {
87 return isRelativePath(p) ? p : './' + p;
88 }((0, _path.relative)((0, _path.dirname)(filenameAbs), fileAbsPath));
89
90 // path.replaceWith(t.stringLiteral(relPath));
91 path.get('arguments.0').replaceWith(t.stringLiteral(relPath));
92 return;
93 }
94
95 if (config.module.loaders.some(function (l) {
96 return l.test.test(filePath) || l.test.test(fileAbsPath);
97 })) {
98 if (isJSFile(fileAbsPath) && skipJs) {
99 // js and jsx files in loaders is unsupported by webpack-loader plugin.
100 // all babel settings in loader will be skipped`
101 return;
102 }
103
104 var webPackResult = (0, _runWebPackSync2.default)({
105 path: loaders + fileAbsPath,
106 configPath: compiledConfigPath,
107 config: config,
108 verbose: verbose
109 });
110
111 var expr = processWebPackResult(webPackResult, config);
112
113 if (expr !== null) {
114 if (expr.type === 'FunctionExpression') {
115 path.remove();
116 } else {
117 path.replaceWith(expr);
118 }
119 } else {
120 path.remove();
121 }
122 }
123 }
124 }
125 };
126};
127
128var _path = require('path');
129
130var _enhancedResolve = require('enhanced-resolve');
131
132var _babylon = require('babylon');
133
134var _template = require('lodash/template');
135
136var _template2 = _interopRequireDefault(_template);
137
138var _babelTraverse = require('babel-traverse');
139
140var _babelTraverse2 = _interopRequireDefault(_babelTraverse);
141
142var _runWebPackSync = require('./runWebPackSync');
143
144var _runWebPackSync2 = _interopRequireDefault(_runWebPackSync);
145
146var _memoize = require('./memoize');
147
148var _memoize2 = _interopRequireDefault(_memoize);
149
150var _babelTypes = require('babel-types');
151
152var _safe = require('colors/safe');
153
154var _safe2 = _interopRequireDefault(_safe);
155
156function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
157
158function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
159
160var processWebPackResult = function processWebPackResult(webPackResult) {
161 var _ref = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
162
163 var _ref$output = _ref.output;
164 _ref$output = _ref$output === undefined ? {} : _ref$output;
165 var _ref$output$publicPat = _ref$output.publicPath;
166 var publicPath = _ref$output$publicPat === undefined ? '' : _ref$output$publicPat;
167
168 var webpackResultAst = (0, _babylon.parse)(webPackResult);
169 var expr = null;
170
171 // without ExtractTextPlugin css-loader result looks like `blabla.locals = {...blbala}`
172 (0, _babelTraverse2.default)(webpackResultAst, {
173 FunctionExpression: function FunctionExpression(pathFn) {
174 if (pathFn.node.params.length >= 2 && pathFn.node.params[1].name === 'exports') {
175 pathFn.traverse({
176 AssignmentExpression: function AssignmentExpression(path) {
177 if (path.node.left.property && path.node.left.property.name === 'locals') {
178 expr = path.node.right;
179 }
180 }
181 });
182 }
183 }
184 });
185
186 // with ExtractTextPlugin css-loader result looks like `module.exports = {...blbala}`
187 if (expr === null) {
188 (0, _babelTraverse2.default)(webpackResultAst, {
189 FunctionExpression: function FunctionExpression(pathFn) {
190 if (pathFn.node.params.length >= 2 && pathFn.node.params[1].name === 'exports') {
191 pathFn.traverse({
192 AssignmentExpression: function AssignmentExpression(path) {
193 if (path.node.left.property && path.node.left.property.name === 'exports') {
194 expr = path.node.right;
195 }
196 },
197 BinaryExpression: function BinaryExpression(pathBin) {
198 pathBin.traverse({
199 MemberExpression: function MemberExpression(pathM) {
200 if (pathM.node.object.name === '__webpack_require__' && pathM.node.property.name === 'p') {
201 pathM.replaceWith((0, _babelTypes.StringLiteral)(publicPath)); // eslint-disable-line
202 }
203 }
204 });
205 }
206 });
207 }
208 }
209 });
210 }
211
212 return _babelTraverse2.default.removeProperties(expr);
213};
214
215// memoize resolver instance
216var getEnhancedResolver = (0, _memoize2.default)(function (_ref2) {
217 var configResolve = _ref2.resolve;
218 return _enhancedResolve.ResolverFactory.createResolver(_extends({
219 fileSystem: new _enhancedResolve.SyncNodeJsInputFileSystem()
220 }, configResolve, configResolve && (configResolve.modules || configResolve.modulesDirectories) && {
221 modules: [].concat(_toConsumableArray(configResolve.modules || []), _toConsumableArray(configResolve.modulesDirectories || []))
222 }));
223});
224
225var localInteropRequire = function localInteropRequire(path) {
226 require('babel-register');
227 var res = require((0, _path.resolve)(process.cwd(), path));
228 if ('default' in res) {
229 return res.default;
230 }
231 return res;
232};
233
234// https://github.com/webpack/node-libs-browser
235var internalNodeModules = {
236 assert: 1,
237 buffer: 1,
238 child_process: 1,
239 cluster: 1,
240 console: 1,
241 constants: 1,
242 crypto: 1,
243 dgram: 1,
244 dns: 1,
245 domain: 1,
246 events: 1,
247 fs: 1,
248 http: 1,
249 https: 1,
250 module: 1,
251 net: 1,
252 os: 1,
253 path: 1,
254 process: 1,
255 punycode: 1,
256 querystring: 1,
257 readline: 1,
258 repl: 1,
259 stream: 1,
260 string_decoder: 1,
261 sys: 1,
262 timers: 1,
263 tls: 1,
264 tty: 1,
265 url: 1,
266 util: 1,
267 vm: 1,
268 zlib: 1
269};
270
271var resolveFilePath = function resolveFilePath(resolver, filenameAbs, filePath) {
272 try {
273 return resolver.resolveSync({}, (0, _path.dirname)(filenameAbs), filePath);
274 } catch (e) {
275 if (!(filePath in internalNodeModules)) {
276 throw e;
277 }
278 }
279 return undefined;
280};
281
282var isInAbsResolveModulesPath = (0, _memoize2.default)(function (_ref3) {
283 var _ref3$resolve = _ref3.resolve;
284 _ref3$resolve = _ref3$resolve === undefined ? {} : _ref3$resolve;
285 var _ref3$resolve$modules = _ref3$resolve.modules;
286 var modules = _ref3$resolve$modules === undefined ? [] : _ref3$resolve$modules;
287 var _ref3$resolve$modules2 = _ref3$resolve.modulesDirectories;
288 var modulesDirectories = _ref3$resolve$modules2 === undefined ? [] : _ref3$resolve$modules2;
289
290 // support only absolute pathes in resolve.modules for js and jsx files
291 // because node_modules aliasing is a bad practice
292 var absPathes = [].concat(_toConsumableArray(modules), _toConsumableArray(modulesDirectories)).filter(function (p) {
293 return p === (0, _path.resolve)(p);
294 });
295
296 return function (fileAbsPath) {
297 return absPathes.some(function (p) {
298 return fileAbsPath.indexOf(p) === 0;
299 });
300 };
301});
302
303var isJSFile = function isJSFile(fileAbsPath) {
304 var test = /\.jsx?$/;
305 return test.test(fileAbsPath);
306};
307
308var isRelativePath = function isRelativePath(fileAbsPath) {
309 return fileAbsPath.indexOf('.') === 0;
310};
311
312var warn = function () {
313 var msgs = {};
314
315 return function (message) {
316 if (message in msgs) {
317 return;
318 }
319
320 msgs[message] = true;
321
322 console.error( // eslint-disable-line
323 _safe2.default.yellow(message));
324 };
325}();
\No newline at end of file