天天看點

Yii2 中使用ts

Yii2 中使用ts

在運作環境 vagrant Ubuntu box 中安裝 sass ,typescript等

安裝需要的軟體:

sudo su -c "gem install sass" # 可選,安裝sass
sudo su -c "npm install -g typescript" # 可選,ts指令
sudo su -c "npm install -g less" # 可選,less指令
sudo su -c "npm install stylus -g" # 可選,stylus指令
sudo su -c "npm install -g coffee-script" # 可選,coffee指令
           

上面的

npm

指令依賴 系統已安裝好

ruby

,

node

上面的gem,npm指令在 windows的cmd中可以運作的

使用的是 Advanced 模闆,修改

common/config/main.php

(如果是 Basic 模闆,修改

config/web.php

檔案),在

components

數組中添加

assetManager

元素 配置

\'assetManager\' => [
            \'converter\' => [
                \'class\' => \'yii\web\AssetConverter\',
                \'commands\' => [
                    \'scss\' => [\'css\', \'sass {from} {to} --sourcemap\'],
                    // 其他指令
                    \'less\' => [\'css\', \'lessc {from} {to} --no-color --source-map\'],
                    \'sass\' => [\'css\', \'sass {from} {to} --sourcemap\'],
                    \'styl\' => [\'css\', \'stylus < {from} > {to}\'],
                    \'coffee\' => [\'js\', \'coffee -p {from} > {to}\'],
                    \'ts\' => [\'js\', \'tsc --out {to} {from}\'],
                ],
            ],
        ],
           

效果類似如下圖:

Yii2 中使用ts

在 AppAsset.php 中直接引入 ts,sass 檔案

class AppAsset extends AssetBundle
{
    public $basePath = \'@webroot\';
    public $baseUrl = \'@web\';
 
    public $css = [
        \'css/index.scss\', // 引入 scss 檔案
    ];
    public $js = [
        \'js/index.ts\', //引入 ts 檔案
    ];
    // 其他内容...
}
           

index.ts 示範内容

let myName = "hello";
           

最後網頁自動導入的是 index.js,裝換的内容是:

var myName = "hello";
           

當編輯 上面的

index.css

或者

index.ts

,就會裝換為對應的 css 或者 js 檔案了.

References
  1. yii2 清楚如何使用ts了
  2. 5分鐘上手TypeScript
  3. Less 使用方法 安裝
  4. Get styling with Stylus
  5. CoffeeScript 中文
  6. Yii2-資源管理(Assets) 使用資源轉換器