UNPKG

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