Yii - 资源转换

开发人员通常不编写 CSSJS 代码,而是使用扩展语法,例如 LESS、SCSS、Stylus for CSS 和 TypeScript、CoffeeScript for JS。然后他们使用特殊工具将这些文件转换为真正的 CSS 和 JS。

Yii 中的资源管理器会自动将扩展语法中的资源转换为 CSS 和 JS。当视图呈现时,它将在页面中包含 CSS 和 JS 文件,而不是扩展语法中的原始资源。

步骤 1 − 以这种方式修改 DemoAsset.php 文件。

<?php
   namespace app\assets;
   use yii\web\AssetBundle;
   use yii\web\View;
   class DemoAsset extends AssetBundle {
      public $basePath = '@webroot';
      public $baseUrl = '@web';
      public $js = [
         'js/demo.js',
         'js/greeting.ts'
      ];
      public  $jsOptions = ['position' => View::POS_HEAD];
   }
?>

我们刚刚添加了一个 typescript 文件。

步骤 2 − 在 web/js 目录中,使用以下代码创建一个名为 greeting.ts 的文件。

class Greeter {
   constructor(public greeting: string) { }
   greet() {
      return this.greeting;
   }
};
var greeter = new Greeter("Hello from typescript!");
console.log(greeter.greet());

在上面的代码中,我们定义了一个 Greeter 类,它只有一个方法 greet()。我们将问候语写入 chrome 控制台。

步骤 3 − 转到 URL http://localhost:8080/index.php。您会注意到 greeting.ts 文件已转换为 Greeting.js 文件,如以下屏幕截图所示。

Greeting Ts File

以下是输出。

Greeting Ts File Output