Coder Social home page Coder Social logo

prettier-loader's Introduction

prettier-loader

Prettier loader for Webpack.


Travis Coverage Status Snyk Vulnerabilities for npm package version downloads Node version support MIT License PRs Welcome Code of Conduct

Purpose

Prettier is one of the best tools that really help developers not to waste time on codestyle.

Listed below are some of the ways one could employ prettier in a project:

  • Editor Integration

    • Pros:

      • no overhead bootstrapping code
      • autoformatting on every save
    • Cons:

      • every developer needs to setup and configure editor's plugin manually
      • teammates can have conflicting plugin settings that might override default settings in an unpredictable way. Or one could forget to install node_modules and a globally installed prettier will be used instead, which might be of older version, etc. This leads to frustrating hiccups in the workflow and, potentially, bugs.
  • Pre-commit Hook

    • Pros:

      • works in the background (i.e. developer doesn't have to think about it)
      • consistent prettier settings in the project
    • Cons:

      • you can not see prettier changes on save
  • Watching For Changes

    • Pros:
      • no overhead bootstrapping code
      • autoformatting on every save
      • works in the background
      • consistent prettier settings in the project
    • Cons:
      • if you already have another watcher (e.g. webpack-dev-server or watchman), you'll be wasting resources and your bundler will be triggered twice on every change: first by user, then by prettier formatting
  • CLI

    • Pros:
      • no overhead bootstrapping code
    • Cons:
      • you can not see prettier changes on save
      • prone to errors unless stored somewhere (e.g. npm-scripts)
  • This Webpack Loader

    • Pros:
      • autoformatting on every save (if working with webpack-dev-server)
      • works in the background
      • consistent prettier settings in the project
      • updates all the codebase when new prettier version is released
    • Cons:
      • works only on webpack-dependent projects

In short, idea is to make source code auto-prettier-fy on every save. But to do it in a cross-IDE manner. Use of webpack, eliminates the need to install and configure plugins on each developer's machine and also provides better efficency, as no other watchers are needed.

Features

  • support prettier configuration files: .prettierrc, prettier.config.js, "prettier" key in your package.json file
  • support of ignoring code using both comments and .prettierignore file
  • override configuration files in loader options
  • zero configuration of loader options for supporting all features out of the box

Requirements

  • webpack >= 2
  • prettier >= 1.6

Create an issue on pr, if you really need to support Webpack 1.

Installation

npm install prettier-loader prettier --save-dev

Usage

Minimal config example

// webpack.config.js
module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: {
          loader: 'prettier-loader',
          exclude: /node_modules/,
        }
      }
    ]
  }
};

Full config example with description

// webpack.config.js
module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: {
          loader: 'prettier-loader',

          // force this loader to run first if it's not first in loaders list
          enforce: 'pre',

          // avoid running prettier on all the files!
          // use it only on your source code and not on dependencies!
          exclude: /node_modules/,
          
          // additional prettier options assigned to options in
          // - .prettierrc,
          // - prettier.config.js,
          // - "prettier" property in package.json
          options: {
            trailingComma: 'es5',
            tabWidth: 4,
            
            // additional options object for resolveConfig method
            // @see https://prettier.io/docs/en/api.html#prettierresolveconfigfilepath-options
            resolveConfigOptions: {
              editorconfig: true,
              config: 'config/prettier.config.js'
            },

            // skip rewriting source file.
            // if true, only prettier the output
            skipRewritingSource: false,

            // skip prettifying file at startup.
            // if true, prettier will be triggered after the modification of a file
            ignoreInitial: false,
          },
        }
      }
    ]
  }
};

Working with HTML preprocessor

If you work with HTML preprocessor (Twig, EJS, Nunjucks, ...), you may want to process the output stream. Still you don't want the input template to be rewritten with the output. In that case, you'll need to tell the loader to keep the source file unchanged.

// webpack.config.js
module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.njk?$/,
        use: [
          {
            loader: 'html-loader',
          },
          {
            loader: 'prettier-loader',
            options: {
              skipRewritingSource: true,
            },
          },
          {
            loader: 'nunjucks-html-loader',
          },
        ],
      }
    ]
  }
};

Pro Tip

Install and use it only in development environment if you minimize code for production, don't do unnecessary work!

Known issue

As a loader, that is modifying source code, it has known issue with double compilation in watch mode. With current webpack API this problem can not be solved (the same problem exists in other similar projects). Webpack maintainers are not going to help with this.

Contributing

All pull requests that respect next rules are welcome:

  • Before opening pull request to this repo run npm t to lint, prettify and run test on code.

  • All bugfixes and features should contain tests.

License

MIT License

Copyright (c) 2017 Oleg Repin

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

prettier-loader's People

Contributors

astik avatar dependabot-preview[bot] avatar iamolegga avatar mergify[bot] avatar opichals avatar tarwich avatar trymoto avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

prettier-loader's Issues

Issue with prettier-loader and *.vue files

If you know how to fix the issue, make a pull request instead.

Select one of these and delete the others:

If asking a question:

  • Question: ...
  • Code (if necessary) below:

If reporting a bug:
Good morning and thank you for this wonderful tool! I just want to bring to your attention that this loader doesn't work properly on *.vue files. It actually doesn't recognize the syntax and confuse it with *.js files. Could you please provide a fix for that!

  • Steps to repeat:
    If you try to add this loader to Storybook Webpack configuration, it will alter the vue files and generate a syntax error
  • Code (if necessary) below:
  • Expected behavior:

  • It should prettify *.vue files

  • Observed behavior:

  • It is not prettifying *.vue files and it outputs a run error!

Disabling prettier-loader when webpack starts


In a project, i have a lot of HTML files defined as entry files thanks to html-webpack-plugin.
Loaders for HTML files are prettier-loader and html-loader.
Each HTML file needs 2 sec of processing by prettier (triggered by prettier-loader.

Cold start will go higher and higher everytime we add new entry HTML files.
As HTML are supposed to be prettified each time we save a file, the processing at startup is unneeded.
Disabling / skipping prettifying at startup would make the startup process way faster.


Naive (still working) approach: we could wait x milliseconds before enabling prettier.

let skip = true;
setTimeout(() => {
  console.log("prettier is now enabled")
  skip = false
}, 5000)

module.exports = async function(source, map) {
  this.cacheable();
  const callback = this.async();

  if (skip) {
    return callback(null, source, map);
  }

Wrong engine version

Currently the engine is set to 8.4.0, which prevents installation on anything else. For example, we're unable to install on 8.4.1

After build uglify plugin fires exception in every file

Every time I tried to build after adding your loader I got problem like this:

ERROR in app/ad64cd4cb288185aae11.js from UglifyJs
Unexpected token: punc ()) [app/ad64cd4cb288185aae11.js:486,0]

With every file in build.

How to use with the .prettierrc file

  • Question: How do I use the .prettierrc file inside the webpack.config.js and inside the prettier-loader options?

Do I need to make additional package.json file changes?
Do I need to reference the .prettierrc inside the options: {} ?

This works, but I want it to read from .prettierrc file that is supposedly supported.
config.module.rules.push({
    test: /\.(js|jsx)?$/,
    use: {
        loader: 'prettier-loader',
        options: {
            parser: "babylon",
            printWidth: 100,
            singleQuote: true,
            tabWidth: 4
        }
    }
});

Now I get this when I run npm start:
"No parser and no filepath given, using 'babylon' the parser now but this will throw an error in the future. Please specify a parser or a filepath so one can be inferred."

Even though I have my .prettierrc file with this setup:

{
    "parser": "babylon",
    "printWidth": 100,
    "singleQuote": true,
    "tabWidth": 4
}

prettier.config.js file spesify path webpack

  • Question: My prettier.config.js not root folder instead of other config folder. And I want change prettier config file path
    In prettier documentation --config ".env/prettier.config.js" work
    But when I use prettier-loader options config webpack return error

Ignored unknown option `{ "configFile": ".env/prettier.config.js"}

error with babel

If you know how to fix the issue, make a pull request instead.

  • hi , I tried using 3.3.0 with my webpack using babel loader and when i add prettier loader to my webpack config file error happens

works fine without prettier loader

here my webpack config:

`const ESLintPlugin = require('eslint-webpack-plugin')

module.exports = {
mode: 'development',
context: __dirname + "/src/js",
entry: "./script.js",
output: {
path: __dirname + "/build",
filename: "bundle.js"
},
module: {
rules: [
{
test: /.m?js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ['@babel/preset-env']
}
}
},
{
test: /.jsx?$/,
use: {
loader: 'prettier-loader',
}
}
]
},
plugins: [new ESLintPlugin({})]
}`

and this is my test js file to be compiled:

async function download(url, ok) { if (ok) { return { name: 'Amin', family: 'Ahmady', website: http://${url}` }
} else {
throw new Error('Downloading Failed!')
}
}

async function save(data, ok) {
if (ok) {
return {
user: data,
ok: !ok,
}
} else {
throw new Error('Save Failed!')
}
}

download('github.com', true)
.then((data) => save(data, true))
.then((data) => console.log(data))
.catch((err) => console.log(err.message))
`

where is the isseu?

my prettier config if needed:
# Ignore artifacts: build node_modules

Ignore/disable prettier didn't works

I tried to add comments like:
// prettier-ignore
// prettier-disable
/* eslint-disable prettier/prettier */
Or add external file '.prettierignore'

But your loder still modify file I'd like to ignore. Is there any way to ignore files when modifying?

Prettier shouldn't be a dependency

Prettier shouldn't be both a dependency and a peerDependency.

It'll force an install of prettier even if you have a higher versioned but still compatible package.

Webpack compile twice when js file changed

Hi,

When I changed a js file, the webpack dev server run the process twice. Do you know how to prevent this?

my config is like:

                    test: /\.jsx?$/,
                    include: {
                        test: [
                            appPath.src.root
                        ]
                    },
                    enforce: 'pre',
                    loader: 'prettier-loader',
                    options: {
                        printWidth: 80,               // Specify the length of line that the printer will wrap on.
                        tabWidth: 4,                  // Specify the number of spaces per indentation-level.
                        useTabs: false,               // Indent lines with tabs instead of spaces.
                        semi: true                   // Print semicolons at the ends of statements.
                    }
                },
                {
                    test: /\.jsx?$/,
                    exclude: {
                        test: appPath.dep.nodeModules
                    },
                    loader: "babel-loader",
                    options: babelConfig({})
                },

webpack output this:

webpack: Compiling...
Hash: 861b7b616fa7df682818
Version: webpack 2.6.1
Time: 192ms
        Asset     Size  Chunks         Chunk Names
app.bundle.js  4.58 MB       0  [big]  main
chunk    {0} app.bundle.js (main) 1.63 MB [entry]
 [../node_modules/react-hot-loader/lib/patch.js] ../~/react-hot-loader/lib/patch.js 214 bytes {0}
 [../node_modules/react-hot-loader/patch.js] ../~/react-hot-loader/patch.js 41 bytes {0}
 [../node_modules/react/react.js] ../~/react/react.js 56 bytes {0}
 [../node_modules/strip-ansi/index.js] ../~/strip-ansi/index.js 163 bytes {0}
 [../node_modules/url/url.js] ../~/url/url.js 25.8 kB {0}
 [../node_modules/webpack-dev-server/client/index.js?http:/localhost:8080] ../~/webpack-dev-server/client?http://localhost:8080/ 6.56 kB {0}
 [../node_modules/webpack-dev-server/client/overlay.js] ../~/webpack-dev-server/client/overlay.js 4.04 kB {0}
 [../node_modules/webpack-dev-server/client/socket.js] ../~/webpack-dev-server/client/socket.js 1.04 kB {0}
 [../node_modules/webpack/buildin/harmony-module.js] ../~/webpack/buildin/harmony-module.js 753 bytes {0}
    [0] multi webpack-dev-server/client?http://localhost:8080/ webpack/hot/dev-server react-hot-loader/patch ./src/index.js 64 bytes {0}
 [../node_modules/webpack/hot/dev-server.js] ../~/webpack/hot/dev-server.js 2.21 kB {0}
 [../node_modules/webpack/hot/emitter.js] ../~/webpack/hot/emitter.js 77 bytes {0}
 [../node_modules/webpack/hot/log-apply-result.js] ../~/webpack/hot/log-apply-result.js 1.2 kB {0}
 [./src/app.js] ./src/app.js 892 bytes {0} [built]
 [./src/index.js] ./src/index.js 787 bytes {0}
     + 446 hidden modules
webpack: Compiled successfully.
webpack: Compiling...
Hash: 861b7b616fa7df682818
Version: webpack 2.6.1
Time: 89ms
        Asset     Size  Chunks         Chunk Names
app.bundle.js  4.58 MB       0  [big]  main
chunk    {0} app.bundle.js (main) 1.63 MB [entry]
 [../node_modules/react-hot-loader/lib/patch.js] ../~/react-hot-loader/lib/patch.js 214 bytes {0}
 [../node_modules/react-hot-loader/patch.js] ../~/react-hot-loader/patch.js 41 bytes {0}
 [../node_modules/react/react.js] ../~/react/react.js 56 bytes {0}
 [../node_modules/strip-ansi/index.js] ../~/strip-ansi/index.js 163 bytes {0}
 [../node_modules/url/url.js] ../~/url/url.js 25.8 kB {0}
 [../node_modules/webpack-dev-server/client/index.js?http:/localhost:8080] ../~/webpack-dev-server/client?http://localhost:8080/ 6.56 kB {0}
 [../node_modules/webpack-dev-server/client/overlay.js] ../~/webpack-dev-server/client/overlay.js 4.04 kB {0}
 [../node_modules/webpack-dev-server/client/socket.js] ../~/webpack-dev-server/client/socket.js 1.04 kB {0}
 [../node_modules/webpack/buildin/harmony-module.js] ../~/webpack/buildin/harmony-module.js 753 bytes {0}
    [0] multi webpack-dev-server/client?http://localhost:8080/ webpack/hot/dev-server react-hot-loader/patch ./src/index.js 64 bytes {0}
 [../node_modules/webpack/hot/dev-server.js] ../~/webpack/hot/dev-server.js 2.21 kB {0}
 [../node_modules/webpack/hot/emitter.js] ../~/webpack/hot/emitter.js 77 bytes {0}
 [../node_modules/webpack/hot/log-apply-result.js] ../~/webpack/hot/log-apply-result.js 1.2 kB {0}
 [./src/app.js] ./src/app.js 892 bytes {0} [built]
 [./src/index.js] ./src/index.js 787 bytes {0}
     + 446 hidden modules
webpack: Compiled successfully.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.