Snippet - Run Prettier on a file or string

3 years ago

IDEs already do a great job of auto-formatting based on your configuration, but sometimes you need to prettify existing files. Here is a simple snippet for doing just this.

prettier-format.js

const fs = require('fs')
const path = require('path')
const prettier = require('prettier')

const prettierString = fileString => {
  const prettierConfig = {
    jsxBracketSameLine: true,
    printWidth: 120,
    semi: false,
    singleQuote: true,
    parser: 'babel'
  }
  return prettier.format(fileString, prettierConfig)
}

const prettierFile = file => {
  let fileString = fs.readFileSync(file).toString()
  fileString = prettierString(fileString)
  fs.writeFileSync(file, fileString)
}

module.exports = { prettierFile, prettierString }

foo.js

const path = require('path')
const { prettierFile, prettierString } = require('./prettier-format')
prettierFile(path.join(__dirname, 'src/MyComponent.js'))
const prettierCode = prettierString('console.log("foo");') // Removes semicolon and changes to single quotes based on config
Discuss on Twitter