# 在项目中使用  Dead Simple LESS CSS Watch Compiler 来自动生成 css 文件

- Link: https://www.ixiqin.com/2022/04/07/in-the-project-use-dead-simple-less-css-watch-compiler-to-automatically-generate-the-css-file/
- Published: 2022-04-07T13:28:08+08:00
- Author: 白宦成

文章目录

 [Toggle](https://www.ixiqin.com/2022/04/07/in-the-project-use-dead-simple-less-css-watch-compiler-to-automatically-generate-the-css-file/#)

 * [教程](https://www.ixiqin.com/2022/04/07/in-the-project-use-dead-simple-less-css-watch-compiler-to-automatically-generate-the-css-file/#%e6%95%99%e7%a8%8b)
    - [安装](https://www.ixiqin.com/2022/04/07/in-the-project-use-dead-simple-less-css-watch-compiler-to-automatically-generate-the-css-file/#%e5%ae%89%e8%a3%85)
    - [配置](https://www.ixiqin.com/2022/04/07/in-the-project-use-dead-simple-less-css-watch-compiler-to-automatically-generate-the-css-file/#%e9%85%8d%e7%bd%ae)
 * [其他](https://www.ixiqin.com/2022/04/07/in-the-project-use-dead-simple-less-css-watch-compiler-to-automatically-generate-the-css-file/#%e5%85%b6%e4%bb%96)
 * [总结](https://www.ixiqin.com/2022/04/07/in-the-project-use-dead-simple-less-css-watch-compiler-to-automatically-generate-the-css-file/#%e6%80%bb%e7%bb%93)

最近在写一个 WordPress 主题来帮助我完成从 WordPress 到微信公众号的实现。在这个过程
中，我需要借助于一些 CSS 的超集，来帮助我完成样式的编写。考虑到 SCSS 的 C++ 依赖
问题，我选择了 Less 来完成。但如果直接使用 lessc 的话，主要面临的问题在于无法检测
文件更新，这样对于需要实时查看效果的我来说，是比较麻烦的。所以我选择使用 Dead Simple
LESS CSS Watch Compiler 来完成自动监控文件变化并刷新的功能。

## 教程

### 安装

执行 npm 命令来安装 Dead Simple LESS CSS Watch Compiler

    ```wp-block-preformatted
    yarn global add less less-watch-compiler 
    ```

安装完成后，你就可以执行命令来监听文件的变化。

### 配置

这里为了方便，我在 WordPress 插件目录中初始化了 npm， 因此，可以非常方便的借助于
npm script 来完成命令的配置。

通过配置了单独的 Build 命令，实现了执行 `npm run build` 就会自动监听 less 文件夹
下的文件，并转换成对应的 css 文件，放置在 css 目录中。

    ```shcb-line-numbers
    {
      "private": true,
      "scripts": {
        "build": "less-watch-compiler ./less ./css"
      },
      "devDependencies": {
        "less": "^4.1.2",
        "less-watch-compiler": "^1.16.3"
      }
    }
    Code language: JSON / JSON with Comments (json)
    ```

## 其他

如果你需要对 less 运行有更多配置的诉求，还可以创建一个 `less-watch-compiler.config.
json` 来配置具体的执行目录。不过我对于这部分没有要求，就直接整个目录来进行配置了。

    ```wp-block-preformatted
    {
        "watchFolder": "<input_folder>",   
        "outputFolder": "<output_folder>",
        "mainFile": "<main-file>",   
        "includeHidden": false,
        "sourceMap": false,
        "plugins": "plugin1,plugin2",
        "lessArgs": "option1=1,option2=2",
        "runOnce": false,
        "enableJs": true
    }
    ```

## 总结

SCSS 因为 node-scss 的编译问题被各种吐槽，虽然换成了 dart-scss ，但历史的阴影还在。
选择了 less 后，通过一些配置，可以让我自己的开发变得更加简单。何乐而不为？
