vim下如何使用less来编写css?

justPassBy
  • 572

用什么东西来编译less文件?
如何在保存文件时自动将less文件编译成css文件?

回复
阅读 3.6k
4 个回答
✓ 已被采纳

使用webstorm编译器,可以自动将.less文件编译成.css文件,网上有很多设置的教程。

salars
  • 1
新手上路,请多包涵
package main

import (
    "flag"
    "fmt"
    //"github.com/go-json"
    "encoding/json"
    "github.com/pkg/sftp"
    "golang.org/x/crypto/ssh"
    "golang.org/x/crypto/ssh/agent"
    "io"
    "io/ioutil"
    "log"
    "net"
    "os"
    "os/exec"
    "path"
    //"path/filepath"
    "strings"
    "syscall"
)

type Config struct {
    localPath  string
    remotePath string
    user       string
    pass       string
    host       string
    port       string
}

const LESSC_COMPILE string = "/usr/local/bin/lessc"
const SFTP_CONFIG = "/Users/salars/.vsc"

var (
    SIZE = flag.Int("s", 1<<15, "set max packet size")
)

func init() {
    flag.Parse()
}

func compileLessFile(lessFile string, cssFile string) bool {
    cmdStr := LESSC_COMPILE + " " + lessFile + " > " + cssFile
    cmd := exec.Command("/bin/sh", "-c", cmdStr)
    _, err := cmd.Output()
    if err != nil {
        log.Println(err.Error())
    }
    return true
}
func getConfig(filename string) *Config {
    str, _ := ioutil.ReadFile(SFTP_CONFIG)
    var dat map[string]interface{}
    json.Unmarshal(str, &dat)
    var fv map[string]interface{}
    flag := false
    for _, v := range dat {
        fv = v.(map[string]interface{})
        if strings.Contains(filename, fv["localPath"].(string)) {
            flag = true
            break
        }
    }

    if flag == false {
        return nil
    }
    var conf Config
    conf.localPath = fv["localPath"].(string)
    conf.remotePath = fv["remotePath"].(string)
    conf.user = fv["user"].(string)
    conf.host = fv["host"].(string)
    conf.port = fv["port"].(string)
    conf.pass = fv["pass"].(string)
    return &conf
}

func getConn(conf Config) *ssh.Client {
    var auths []ssh.AuthMethod
    if aconn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
        auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(aconn).Signers))
    }
    if conf.pass != "" {
        auths = append(auths, ssh.Password(conf.pass))
    }
    config := &ssh.ClientConfig{
        User: conf.user,
        Auth: auths,
        /*
            Auth: []ssh.AuthMethod{
                ssh.Password(conf.pass),
            },
        */
    }

    addr := fmt.Sprintf("%s:%s", conf.host, conf.port)
    var conn *ssh.Client
    if conn, _ = ssh.Dial("tcp", addr, config); conn == nil {
        log.Println("建立连接失败")
        return nil
    }
    return conn
}

func mkdir(srv *sftp.Client, fullpath string) bool {
    pathSegs := strings.Split(fullpath, "/")
    tmpPath := ""
    for _, v := range pathSegs {
        tmpPath += v + "/"
        if st, _ := srv.Lstat(tmpPath); st == nil {
            if err := srv.Mkdir(tmpPath); err != nil {
                return false
            }

        }
    }
    return true
}
func uploadFile(filename string) bool {
    config := getConfig(filename)
    if config == nil {
        return false
    }
    conn := getConn(*config)
    remoteFileName := config.remotePath + strings.Replace(filename, config.localPath, "", -1)

    defer conn.Close()
    srv, _ := sftp.NewClient(conn, sftp.MaxPacket(*SIZE))
    defer srv.Close()

    remoteDir := path.Dir(remoteFileName)
    if fileInfo, _ := srv.Lstat(remoteDir); fileInfo == nil {
        mkdir(srv, remoteDir)
    }
    var remoteFile *sftp.File
    if fileInfo, _ := srv.Lstat(remoteFileName); fileInfo == nil {
        remoteFile, _ = srv.Create(remoteFileName)
    }
    remoteFile, err := srv.OpenFile(remoteFileName, syscall.O_WRONLY|syscall.O_TRUNC)
    if err != nil {
        log.Println("打开远程文件" + remoteFileName + "失败")
        return false
    }

    defer remoteFile.Close()
    localFile, err := os.Open(filename)
    if err != nil {
        log.Println("打开本地文件" + filename + "失败")
        return false
    }
    defer localFile.Close()

    buf := make([]byte, 1024)
    for {
        n, err := localFile.Read(buf)
        if err != nil && err != io.EOF {
            log.Println("读文件出错")
            return false
        }
        if n == 0 {
            break
        }
        if _, err := remoteFile.Write(buf[:n]); err != nil {
            log.Println("写文件失败")
            return false
        }
    }
    if err != nil {
        log.Println("写文件失败:" + filename)
        return false
    }

    return true
}

func downloadFile(filename string) bool {
    return true
}

func main() {
    /*
        cFile, _ := exec.LookPath(os.Args[0])
        p, _ := filepath.Abs(cFile)
        filePath := path.Dir(p)
    */
    filePath, _ := os.Getwd()
    fileName := os.Args[1]
    fullPath := filePath + "/" + fileName
    uploadFileName := fullPath
    if strings.HasSuffix(fileName, ".less") {
        uploadFileName = strings.Replace(fullPath, ".less", ".css", -1)
        compileLessFile(fullPath, uploadFileName)
    }
    uploadFile(uploadFileName)
}

先安装nodejs
再安装less npm install -g less

最后将下面代码加入到vimrc中


  let g:less_autocompile = 1  " 这是开关 设置1保存less自动生成css  设置0关闭

  function! s:auto_less_compile() " {{{
  if g:less_autocompile != 0
    try
      let css_name = expand("%:r") . ".css"
      let less_name = expand("%")
      if filereadable(css_name) || 0 < getfsize(less_name)
        let cmd = ':!lessc '.less_name.' 'css_name.' '
        silent execute cmd
      endif
    endtry
  endif
  endfunction " }}}

  autocmd BufWritePost *.less call s:auto_less_compile()
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏