文章

Prettier vue file with Sublime Text

Prettier has yet to support Vue‘s single file component (.vue file), so Sublime Text’s SublimeJsPrettier cannot do so. My current solution is using Sublime’s build system.

Installs

  • in Sublime Text, install hooks.
  • install prettier (npm install prettier --save-dev)
  • install html-script-hook (npm install html-script-hook --save-dev)

Setup

In your sublime project file, we will hook the on_post_save event to do a sublime build command, where it will run a node script.

    "settings":
    {
        "on_post_save_project": [
            {
                "command": "build",
                "scope": "window"
            }
        ]
    },
    "build_systems":[
        {
            "name": "vue-prettier",
            "cmd": ["node", "prettierVueFile.js", "$file"],
            "working_dir": "c:\\workspace\\myapp",
            "selector": "text.html.vue"
        }
    ]

The node script is quite simple:

const prettier = require('prettier');
const options = require('./package.json').prettier || {};
const fs = require('fs');
const parser = require('html-script-hook');

const file = process.argv[2];
const source = fs.readFileSync(file, 'utf8');

const result = parser(source, {
    scriptCallback: function(code) {
        return `\n\n${prettier.format(code, options)}\n`;
    },
    padLineNo: true
});

fs.writeFileSync(file, result, { encoding: 'utf8' });
console.log(`run prettier on ${file}`);

In this way when you save your vue file, the <script> section of vue file will be prettier! Note that I store the prettier config at package.json , which will be supported by prettier in future.

*