UNPKG

2.48 kBJavaScriptView Raw
1var ngAnnotate = require('ng-annotate');
2var utils = require('loader-utils');
3var SourceMapConsumer = require('source-map').SourceMapConsumer;
4var SourceMapGenerator = require('source-map').SourceMapGenerator;
5
6function loadPlugins(pluginNames) {
7 var pluginNames = pluginNames || [];
8 return pluginNames.map(function(name) {
9 return require(name);
10 });
11}
12
13function getOptions(sourceMapEnabled, filename) {
14 var options = utils.parseQuery(this.query);
15
16 //"add" should be a default option if not overrided in query
17 if (options.add === undefined) {
18 options.add = true;
19 }
20
21 if (sourceMapEnabled && options.map === undefined) {
22 options.map = {
23 inline: false,
24 inFile: filename,
25 };
26 }
27
28 if (options.plugin) {
29 options.plugin = loadPlugins(options.plugin);
30 }
31
32 return options;
33}
34
35function mergeSourceMaps(inputSourceMap, annotateMap) {
36 var outputSourceMap;
37 var sourceMapEnabled = this.sourceMap;
38 var filename = this.resourcePath;
39 this.cacheable && this.cacheable();
40
41 // Using BabelJS as an example,
42 // https://github.com/babel/babel/blob/d3a73b87e9007104cb4fec343f0cfb9e1c67a4ec/packages/babel/src/transformation/file/index.js#L465
43 // See also vinyl-sourcemaps-apply (used by gulp-ng-annotate) - https://github.com/floridoo/vinyl-sourcemaps-apply/blob/master/index.js
44 if (sourceMapEnabled && inputSourceMap) {
45 if (annotateMap) {
46 var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(annotateMap));
47 generator.applySourceMap(new SourceMapConsumer(inputSourceMap), filename);
48
49 outputSourceMap = generator.toJSON();
50
51 //Should be set to avoid '../../file is not in SourceMap error https://github.com/huston007/ng-annotate-loader/pull/11'
52 outputSourceMap.sourceRoot = '';
53 //Copy file name from incoming file because it is empty by some unknown reaon
54 outputSourceMap.file = inputSourceMap.file;
55 } else {
56 outputSourceMap = inputSourceMap;
57 }
58 }
59
60 return outputSourceMap;
61}
62
63module.exports = function(source, inputSourceMap) {
64 var sourceMapEnabled = this.sourceMap;
65 var filename = this.resourcePath;
66 this.cacheable && this.cacheable();
67
68 var annotateResult = ngAnnotate(source, getOptions.call(this, sourceMapEnabled, filename));
69 var outputSourceMap = mergeSourceMaps.call(this, inputSourceMap, annotateResult.map);
70
71 this.callback(null, annotateResult.src || source, outputSourceMap);
72};
\No newline at end of file