You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

163 lines
6.0 KiB

  1. <?php
  2. namespace app\admin\command;
  3. use think\console\Command;
  4. use think\console\Input;
  5. use think\console\input\Option;
  6. use think\console\Output;
  7. use think\Exception;
  8. class Min extends Command
  9. {
  10. /**
  11. * 路径和文件名配置
  12. */
  13. protected $options = [
  14. 'cssBaseUrl' => 'public/assets/css/',
  15. 'cssBaseName' => '{module}',
  16. 'jsBaseUrl' => 'public/assets/js/',
  17. 'jsBaseName' => 'require-{module}',
  18. ];
  19. protected function configure()
  20. {
  21. $this
  22. ->setName('min')
  23. ->addOption('module', 'm', Option::VALUE_REQUIRED, 'module name(frontend or backend),use \'all\' when build all modules', null)
  24. ->addOption('resource', 'r', Option::VALUE_REQUIRED, 'resource name(js or css),use \'all\' when build all resources', null)
  25. ->addOption('optimize', 'o', Option::VALUE_OPTIONAL, 'optimize type(uglify|closure|none)', 'none')
  26. ->setDescription('Compress js and css file');
  27. }
  28. protected function execute(Input $input, Output $output)
  29. {
  30. $module = $input->getOption('module') ?: '';
  31. $resource = $input->getOption('resource') ?: '';
  32. $optimize = $input->getOption('optimize') ?: 'none';
  33. if (!$module || !in_array($module, ['frontend', 'backend', 'all'])) {
  34. throw new Exception('Please input correct module name');
  35. }
  36. if (!$resource || !in_array($resource, ['js', 'css', 'all'])) {
  37. throw new Exception('Please input correct resource name');
  38. }
  39. $moduleArr = $module == 'all' ? ['frontend', 'backend'] : [$module];
  40. $resourceArr = $resource == 'all' ? ['js', 'css'] : [$resource];
  41. $minPath = __DIR__ . DS . 'Min' . DS;
  42. $publicPath = ROOT_PATH . 'public' . DS;
  43. $tempFile = $minPath . 'temp.js';
  44. $nodeExec = '';
  45. if (!$nodeExec) {
  46. if (IS_WIN) {
  47. // Winsows下请手动配置配置该值,一般将该值配置为 '"C:\Program Files\nodejs\node.exe"',除非你的Node安装路径有变更
  48. $nodeExec = 'C:\Program Files\nodejs\node.exe';
  49. if (file_exists($nodeExec)) {
  50. $nodeExec = '"' . $nodeExec . '"';
  51. } else {
  52. // 如果 '"C:\Program Files\nodejs\node.exe"' 不存在,可能是node安装路径有变更
  53. // 但安装node会自动配置环境变量,直接执行 '"node.exe"' 提高第一次使用压缩打包的成功率
  54. $nodeExec = '"node.exe"';
  55. }
  56. } else {
  57. try {
  58. $nodeExec = exec("which node");
  59. if (!$nodeExec) {
  60. throw new Exception("node environment not found!please install node first!");
  61. }
  62. } catch (Exception $e) {
  63. throw new Exception($e->getMessage());
  64. }
  65. }
  66. }
  67. foreach ($moduleArr as $mod) {
  68. foreach ($resourceArr as $res) {
  69. $data = [
  70. 'publicPath' => $publicPath,
  71. 'jsBaseName' => str_replace('{module}', $mod, $this->options['jsBaseName']),
  72. 'jsBaseUrl' => $this->options['jsBaseUrl'],
  73. 'cssBaseName' => str_replace('{module}', $mod, $this->options['cssBaseName']),
  74. 'cssBaseUrl' => $this->options['cssBaseUrl'],
  75. 'jsBasePath' => str_replace(DS, '/', ROOT_PATH . $this->options['jsBaseUrl']),
  76. 'cssBasePath' => str_replace(DS, '/', ROOT_PATH . $this->options['cssBaseUrl']),
  77. 'optimize' => $optimize,
  78. 'ds' => DS,
  79. ];
  80. //源文件
  81. $from = $data["{$res}BasePath"] . $data["{$res}BaseName"] . '.' . $res;
  82. if (!is_file($from)) {
  83. $output->error("{$res} source file not found!file:{$from}");
  84. continue;
  85. }
  86. if ($res == "js") {
  87. $content = file_get_contents($from);
  88. preg_match("/require\.config\(\{[\r\n]?[\n]?+(.*?)[\r\n]?[\n]?}\);/is", $content, $matches);
  89. if (!isset($matches[1])) {
  90. $output->error("js config not found!");
  91. continue;
  92. }
  93. $config = preg_replace("/(urlArgs|baseUrl):(.*)\n/", '', $matches[1]);
  94. $data['config'] = $config;
  95. }
  96. // 生成压缩文件
  97. $this->writeToFile($res, $data, $tempFile);
  98. $output->info("Compress " . $data["{$res}BaseName"] . ".{$res}");
  99. // 执行压缩
  100. $command = "{$nodeExec} \"{$minPath}r.js\" -o \"{$tempFile}\" >> \"{$minPath}node.log\"";
  101. if ($output->isDebug()) {
  102. $output->warning($command);
  103. }
  104. echo exec($command);
  105. }
  106. }
  107. if (!$output->isDebug()) {
  108. @unlink($tempFile);
  109. }
  110. $output->info("Build Successed!");
  111. }
  112. /**
  113. * 写入到文件
  114. * @param string $name
  115. * @param array $data
  116. * @param string $pathname
  117. * @return mixed
  118. */
  119. protected function writeToFile($name, $data, $pathname)
  120. {
  121. $search = $replace = [];
  122. foreach ($data as $k => $v) {
  123. $search[] = "{%{$k}%}";
  124. $replace[] = $v;
  125. }
  126. $stub = file_get_contents($this->getStub($name));
  127. $content = str_replace($search, $replace, $stub);
  128. if (!is_dir(dirname($pathname))) {
  129. mkdir(strtolower(dirname($pathname)), 0755, true);
  130. }
  131. return file_put_contents($pathname, $content);
  132. }
  133. /**
  134. * 获取基础模板
  135. * @param string $name
  136. * @return string
  137. */
  138. protected function getStub($name)
  139. {
  140. return __DIR__ . DS . 'Min' . DS . 'stubs' . DS . $name . '.stub';
  141. }
  142. }