UNPKG

gulp-json-angular-translate

Version:

Gulp plugin to convert json files to angular-translate js files

75 lines (63 loc) 2.5 kB
'use strict'; var through = require('through2'), gutil = require('gulp-util'), jsBeautify = require('js-beautify').js_beautify, toSingleQuotes = require('to-single-quotes-shahata'), _ = require('lodash'); var PLUGIN_NAME = 'gulp-json-angular-translate'; function unflatten(json) { return Object.keys(json).reduce(function (prev, key) { return _.merge(prev, key.split('.').reduceRight(function (prev, curr) { var obj = {}; obj[curr] = prev; return obj; }, json[key])); }, {}); } module.exports = function jsonAngularTranslate(options) { var extractLanguage, contentProcessor; options = _.extend({ moduleName: 'translations', extractLanguage: /..(?=\.[^.]*$)/, hasPreferredLanguage: true, createNestedKeys: true }, options); extractLanguage = typeof(options.extractLanguage) === 'function' ? options.extractLanguage : function (filepath) { return filepath.match(options.extractLanguage)[0]; }; contentProcessor = options.createNestedKeys ? unflatten : _.identity; return through.obj(function doJsonAngularTranslate(file, enc, callback) { if (file.isStream()) { this.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported!')); return callback(); } if (file.isBuffer()) { var result = gutil.template('' + '\'use strict\';\n' + '\n' + 'try {\n' + ' angular.module(\'<%= moduleName %>\');\n' + '} catch (e) {\n' + ' angular.module(\'<%= moduleName %>\', [\'pascalprecht.translate\']);\n' + '}\n' + '\n' + 'angular.module(\'<%= moduleName %>\').config([\'$translateProvider\',\n' + ' function ($translateProvider) {\n' + ' var translations = <%= translations %>;\n' + ' $translateProvider.translations(\'<%= language %>\', translations);\n' + ' $translateProvider.translations(translations);\n' + (options.hasPreferredLanguage ? ' $translateProvider.preferredLanguage(\'<%= language %>\');\n' : '') + ' }\n' + ']);', _.extend({}, options, { language: extractLanguage(file.path), translations: toSingleQuotes(JSON.stringify(contentProcessor(JSON.parse(file.contents.toString())))), file: file })); result = jsBeautify(result, {'indent_size': 2, 'jslint_happy': true}); file.contents = new Buffer(result); file.path = gutil.replaceExtension(file.path, '.js'); this.push(file); callback(); } }); };