Skip to content
This repository has been archived by the owner on Jul 16, 2020. It is now read-only.

Commit

Permalink
feat: Add optional UMD style module export (#19)
Browse files Browse the repository at this point in the history
* feat: Add optional UMD style module export

Add ability to export the locales into an UMD styled export object.

* test: Fix failing tests.
  • Loading branch information
Dobromir Hristov authored and martinlindhe committed Jul 5, 2017
1 parent 35c8d8b commit 4fb7459
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 6 deletions.
6 changes: 4 additions & 2 deletions src/Commands/GenerateInclude.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class GenerateInclude extends Command
*
* @var string
*/
protected $signature = 'vue-i18n:generate';
protected $signature = 'vue-i18n:generate {--umd}';

/**
* The console command description.
Expand All @@ -28,8 +28,10 @@ public function handle()
{
$root = base_path() . config('vue-i18n-generator.langPath');

$umd = $this->option('umd');

$data = (new Generator)
->generateFromPath($root);
->generateFromPath($root, $umd);

$jsFile = base_path() . config('vue-i18n-generator.jsFile');

Expand Down
46 changes: 42 additions & 4 deletions src/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,19 @@ class Generator
{
/**
* @param string $path
* @param boolean $umd
* @return string
* @throws Exception
*/
public function generateFromPath($path)
public function generateFromPath($path, $umd = null)
{
if (!is_dir($path)) {
throw new Exception('Directory not found: '.$path);
}

$locales = [];
$dir = new DirectoryIterator($path);
$jsBody = '';

foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()
Expand All @@ -40,8 +42,15 @@ public function generateFromPath($path)
}
}

return 'export default '
. json_encode($locales, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . PHP_EOL;
$jsonLocales = json_encode($locales, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . PHP_EOL;

if(!$umd) {
$jsBody = $this->getES6Module($jsonLocales);
} else {
$jsBody = $this->getUMDModule($jsonLocales);
}

return $jsBody;
}

/**
Expand Down Expand Up @@ -155,4 +164,33 @@ private function removeExtension($filename)

return mb_substr($filename, 0, $pos);
}
}

/**
* Returns an UMD style module
* @param string $body
* @return string
*/
private function getUMDModule($body)
{
$js = <<<HEREDOC
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.vuei18nLocales = factory());
}(this, (function () { 'use strict';
return {$body}
})));
HEREDOC;
return $js;
}

/**
* Returns an ES6 style module
* @param string $body
* @return string
*/
private function getES6Module($body)
{
return "export default {$body}";
}
}

0 comments on commit 4fb7459

Please sign in to comment.