Giter Site home page Giter Site logo

standard / standard Goto Github PK

View Code? Open in Web Editor NEW
28.9K 473.0 2.3K 3.55 MB

🌟 JavaScript Style Guide, with linter & automatic code fixer

Home Page: https://standardjs.com

License: MIT License

JavaScript 81.89% Shell 18.11%
eslint javascript linter style-guide static-code-analysis development ecmascript standard es6 nodejs

standard's Introduction

Standard - JavaScript Style Guide
JavaScript Standard Style

discord External tests Internal tests status badge old Node test npm version npm downloads Standard - JavaScript Style Guide

Sponsored by    Socket – Supply Chain Dependency Security for JavaScript and npm    Wormhole

EnglishEspañol (Latinoamérica)FrançaisBahasa IndonesiaItaliano (Italian)日本語 (Japanese)한국어 (Korean)Português (Brasil)简体中文 (Simplified Chinese)繁體中文 (Taiwanese Mandarin)

JavaScript style guide, linter, and formatter

This module saves you (and others!) time in three ways:

  • No configuration. The easiest way to enforce code quality in your project. No decisions to make. No .eslintrc files to manage. It just works.
  • Automatically format code. Just run standard --fix and say goodbye to messy or inconsistent code.
  • Catch style issues & programmer errors early. Save precious code review time by eliminating back-and-forth between reviewer & contributor.

Give it a try by running npx standard --fix right now!

Table of Contents

Install

The easiest way to use JavaScript Standard Style is to install it globally as a Node command line program. Run the following command in Terminal:

$ npm install standard --global

Or, you can install standard locally, for use in a single project:

$ npm install standard --save-dev

Note: To run the preceding commands, Node.js and npm must be installed.

Usage

After you've installed standard, you should be able to use the standard program. The simplest use case would be checking the style of all JavaScript files in the current working directory:

$ standard
Error: Use JavaScript Standard Style
  lib/torrent.js:950:11: Expected '===' and instead saw '=='.

If you've installed standard locally, run with npx instead:

$ npx standard

You can optionally pass in a directory (or directories) using the glob pattern. Be sure to quote paths containing glob patterns so that they are expanded by standard instead of your shell:

$ standard "src/util/**/*.js" "test/**/*.js"

Note: by default standard will look for all files matching the patterns: **/*.js, **/*.jsx.

What you might do if you're clever

  1. Add it to package.json

    {
      "name": "my-cool-package",
      "devDependencies": {
        "standard": "*"
      },
      "scripts": {
        "test": "standard && node my-tests.js"
      }
    }
  2. Style is checked automatically when you run npm test

    $ npm test
    Error: Use JavaScript Standard Style
      lib/torrent.js:950:11: Expected '===' and instead saw '=='.
  3. Never give style feedback on a pull request again!

Why should I use JavaScript Standard Style?

The beauty of JavaScript Standard Style is that it's simple. No one wants to maintain multiple hundred-line style configuration files for every module/project they work on. Enough of this madness!

This module saves you (and others!) time in three ways:

  • No configuration. The easiest way to enforce consistent style in your project. Just drop it in.
  • Automatically format code. Just run standard --fix and say goodbye to messy or inconsistent code.
  • Catch style issues & programmer errors early. Save precious code review time by eliminating back-and-forth between reviewer & contributor.

Adopting standard style means ranking the importance of code clarity and community conventions higher than personal style. This might not make sense for 100% of projects and development cultures, however open source can be a hostile place for newbies. Setting up clear, automated contributor expectations makes a project healthier.

For more info, see the conference talk "Write Perfect Code with Standard and ESLint". In this talk, you'll learn about linting, when to use standard versus eslint, and how prettier compares to standard.

Who uses JavaScript Standard Style?

Free MIDIs, MIDI file downloads College essays, AP notes
Your Logo Here

In addition to companies, many community members use standard on packages that are too numerous to list here.

standard is also the top-starred linter in GitHub's Clean Code Linter showcase.

Are there text editor plugins?

First, install standard. Then, install the appropriate plugin for your editor:

Sublime Text

Using Package Control, install SublimeLinter and SublimeLinter-contrib-standard.

For automatic formatting on save, install StandardFormat.

Atom

Install linter-js-standard.

Alternatively, you can install linter-js-standard-engine. Instead of bundling a version of standard it will automatically use the version installed in your current project. It will also work out of the box with other linters based on standard-engine.

For automatic formatting, install standard-formatter. For snippets, install standardjs-snippets.

Visual Studio Code

Install vscode-standard. (Includes support for automatic formatting.)

For JS snippets, install: vscode-standardjs-snippets. For React snippets, install vscode-react-standard.

Vim

Install ale. And add these lines to your .vimrc file.

let g:ale_linters = {
\   'javascript': ['standard'],
\}
let g:ale_fixers = {'javascript': ['standard']}

This sets standard as your only linter and fixer for javascript files and so prevents conflicts with eslint. For linting and automatic fixing on save, add these lines to .vimrc:

let g:ale_lint_on_save = 1
let g:ale_fix_on_save = 1

Alternative plugins to consider include neomake and syntastic, both of which have built-in support for standard (though configuration may be necessary).

Emacs

Install Flycheck and check out the manual to learn how to enable it in your projects.

Brackets

Search the extension registry for "Standard Code Style" and click "Install".

WebStorm (PhpStorm, IntelliJ, RubyMine, JetBrains, etc.)

WebStorm recently announced native support for standard directly in the IDE.

If you still prefer to configure standard manually, follow this guide. This applies to all JetBrains products, including PhpStorm, IntelliJ, RubyMine, etc.

Is there a readme badge?

Yes! If you use standard in your project, you can include one of these badges in your readme to let people know that your code is using the standard style.

JavaScript Style Guide

[![JavaScript Style Guide](https://cdn.rawgit.com/standard/standard/master/badge.svg)](https://github.com/standard/standard)

JavaScript Style Guide

[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)

I disagree with rule X, can you change it?

No. The whole point of standard is to save you time by avoiding bikeshedding about code style. There are lots of debates online about tabs vs. spaces, etc. that will never be resolved. These debates just distract from getting stuff done. At the end of the day you have to 'just pick something', and that's the whole philosophy of standard -- its a bunch of sensible 'just pick something' opinions. Hopefully, users see the value in that over defending their own opinions.

There are a couple of similar packages for anyone who does not want to completely accept standard:

If you really want to configure hundreds of ESLint rules individually, you can always use eslint directly with eslint-config-standard to layer your changes on top. standard-eject can help you migrate from standard to eslint and eslint-config-standard.

Pro tip: Just use standard and move on. There are actual real problems that you could spend your time solving! :P

But this isn't a real web standard!

Of course it's not! The style laid out here is not affiliated with any official web standards groups, which is why this repo is called standard/standard and not ECMA/standard.

The word "standard" has more meanings than just "web standard" :-) For example:

  • This module helps hold our code to a high standard of quality.
  • This module ensures that new contributors follow some basic style standards.

Is there an automatic formatter?

Yes! You can use standard --fix to fix most issues automatically.

standard --fix is built into standard for maximum convenience. Most problems are fixable, but some errors (like forgetting to handle errors) must be fixed manually.

To save you time, standard outputs the message "Run standard --fix to automatically fix some problems" when it detects problems that can be fixed automatically.

How do I ignore files?

Certain paths (node_modules/, coverage/, vendor/, *.min.js, and files/folders that begin with . like .git/) are automatically ignored.

Paths in a project's root .gitignore file are also automatically ignored.

Sometimes you need to ignore additional folders or specific minified files. To do that, add a standard.ignore property to package.json:

"standard": {
  "ignore": [
    "**/out/",
    "/lib/select2/",
    "/lib/ckeditor/",
    "tmp.js"
  ]
}

How do I disable a rule?

In rare cases, you'll need to break a rule and hide the error generated by standard.

JavaScript Standard Style uses ESLint under-the-hood and you can hide errors as you normally would if you used ESLint directly.

Disable all rules on a specific line:

file = 'I know what I am doing' // eslint-disable-line

Or, disable only the "no-use-before-define" rule:

file = 'I know what I am doing' // eslint-disable-line no-use-before-define

Or, disable the "no-use-before-define" rule for multiple lines:

/* eslint-disable no-use-before-define */
console.log('offending code goes here...')
console.log('offending code goes here...')
console.log('offending code goes here...')
/* eslint-enable no-use-before-define */

I use a library that pollutes the global namespace. How do I prevent "variable is not defined" errors?

Some packages (e.g. mocha) put their functions (e.g. describe, it) on the global object (poor form!). Since these functions are not defined or require'd anywhere in your code, standard will warn that you're using a variable that is not defined (usually, this rule is really useful for catching typos!). But we want to disable it for these global variables.

To let standard (as well as humans reading your code) know that certain variables are global in your code, add this to the top of your file:

/* global myVar1, myVar2 */

If you have hundreds of files, it may be desirable to avoid adding comments to every file. In this case, run:

$ standard --global myVar1 --global myVar2

Or, add this to package.json:

{
  "standard": {
    "globals": [ "myVar1", "myVar2" ]
  }
}

Note: global and globals are equivalent.

How do I use experimental JavaScript (ES Next) features?

standard supports the latest ECMAScript features, ES8 (ES2017), including language feature proposals that are in "Stage 4" of the proposal process.

To support experimental language features, standard supports specifying a custom JavaScript parser. Before using a custom parser, consider whether the added complexity is worth it.

To use a custom parser, first install it from npm:

npm install @babel/eslint-parser --save-dev

Then run:

$ standard --parser @babel/eslint-parser

Or, add this to package.json:

{
  "standard": {
    "parser": "@babel/eslint-parser"
  }
}

Can I use a JavaScript language variant, like Flow or TypeScript?

standard supports the latest ECMAScript features. However, Flow and TypeScript add new syntax to the language, so they are not supported out-of-the-box.

For TypeScript, an official variant ts-standard is supported and maintained that provides a very similar experience to standard.

For other JavaScript language variants, standard supports specifying a custom JavaScript parser as well as an ESLint plugin to handle the changed syntax. Before using a JavaScript language variant, consider whether the added complexity is worth it.

TypeScript

ts-standard is the officially supported variant for TypeScript. ts-standard supports all the same rules and options as standard and includes additional TypeScript specific rules. ts-standard will even lint regular javascript files by setting the configuration in tsconfig.json.

npm install ts-standard --save-dev

Then run (where tsconfig.json is located in the working directory):

$ ts-standard

Or, add this to package.json:

{
  "ts-standard": {
    "project": "./tsconfig.json"
  }
}

Note: To include additional files in linting such as test files, create a tsconfig.eslint.json file to use instead.

If you really want to configure hundreds of ESLint rules individually, you can always use eslint directly with eslint-config-standard-with-typescript to layer your changes on top.

Flow

To use Flow, you need to run standard with @babel/eslint-parser as the parser and eslint-plugin-flowtype as a plugin.

npm install @babel/eslint-parser eslint-plugin-flowtype --save-dev

Then run:

$ standard --parser @babel/eslint-parser --plugin flowtype

Or, add this to package.json:

{
  "standard": {
    "parser": "@babel/eslint-parser",
    "plugins": [ "flowtype" ]
  }
}

Note: plugin and plugins are equivalent.

What about Mocha, Jest, Jasmine, QUnit, etc?

To support mocha in test files, add this to the top of the test files:

/* eslint-env mocha */

Or, run:

$ standard --env mocha

Where mocha can be one of jest, jasmine, qunit, phantomjs, and so on. To see a full list, check ESLint's specifying environments documentation. For a list of what globals are available for these environments, check the globals npm module.

Note: env and envs are equivalent.

What about Web Workers and Service Workers?

Add this to the top of web worker files:

/* eslint-env worker */

This lets standard (as well as humans reading the code) know that self is a global in web worker code.

For Service workers, add this instead:

/* eslint-env serviceworker */

What is the difference between warnings and errors?

standard treats all rule violations as errors, which means that standard will exit with a non-zero (error) exit code.

However, we may occasionally release a new major version of standard which changes a rule that affects the majority of standard users (for example, transitioning from var to let/const). We do this only when we think the advantage is worth the cost and only when the rule is auto-fixable.

In these situations, we have a "transition period" where the rule change is only a "warning". Warnings don't cause standard to return a non-zero (error) exit code. However, a warning message will still print to the console. During the transition period, using standard --fix will update your code so that it's ready for the next major version.

The slow and careful approach is what we strive for with standard. We're generally extremely conservative in enforcing the usage of new language features. We want using standard to be light and fun and so we're careful about making changes that may get in your way. As always, you can disable a rule at any time, if necessary.

Can I check code inside of Markdown or HTML files?

To check code inside Markdown files, use standard-markdown.

Alternatively, there are ESLint plugins that can check code inside Markdown, HTML, and many other types of language files:

To check code inside Markdown files, use an ESLint plugin:

$ npm install eslint-plugin-markdown

Then, to check JS that appears inside code blocks, run:

$ standard --plugin markdown '**/*.md'

To check code inside HTML files, use an ESLint plugin:

$ npm install eslint-plugin-html

Then, to check JS that appears inside <script> tags, run:

$ standard --plugin html '**/*.html'

Is there a Git pre-commit hook?

Yes! Hooks are great for ensuring that unstyled code never even makes it into your repo. Never give style feedback on a pull request again!

You even have a choice...

Install your own hook

#!/bin/bash

# Ensure all JavaScript files staged for commit pass standard code style
function xargs-r() {
  # Portable version of "xargs -r". The -r flag is a GNU extension that
  # prevents xargs from running if there are no input files.
  if IFS= read -r -d $'\n' path; then
    echo "$path" | cat - | xargs "$@"
  fi
}
git diff --name-only --cached --relative | grep '\.jsx\?$' | sed 's/[^[:alnum:]]/\\&/g' | xargs-r -E '' -t standard
if [[ $? -ne 0 ]]; then
  echo 'JavaScript Standard Style errors were detected. Aborting commit.'
  exit 1
fi

Use a pre-commit hook

The pre-commit library allows hooks to be declared within a .pre-commit-config.yaml configuration file in the repo, and therefore more easily maintained across a team.

Users of pre-commit can simply add standard to their .pre-commit-config.yaml file, which will automatically fix .js, .jsx, .mjs and .cjs files:

  - repo: https://github.com/standard/standard
    rev: master
    hooks:
      - id: standard

Alternatively, for more advanced styling configurations, use standard within the eslint hook:

  - repo: https://github.com/pre-commit/mirrors-eslint
    rev: master
    hooks:
      - id: eslint
        files: \.[jt]sx?$  # *.js, *.jsx, *.ts and *.tsx
        types: [file]
        additional_dependencies:
          - eslint@latest
          - eslint-config-standard@latest
          # and whatever other plugins...

How do I make the output all colorful and pretty?

The built-in output is simple and straightforward, but if you like shiny things, install snazzy:

$ npm install snazzy

And run:

$ standard | snazzy

There's also standard-tap, standard-json, standard-reporter, and standard-summary.

Is there a Node.js API?

Yes!

async standard.lintText(text, [opts])

Lint the provided source text. An opts object may be provided:

{
  // unique to lintText
  filename: '',         // path of file containing the text being linted

  // common to lintText and lintFiles
  cwd: '',              // current working directory (default: process.cwd())
  fix: false,           // automatically fix problems
  extensions: [],       // file extensions to lint (has sane defaults)
  globals: [],          // custom global variables to declare
  plugins: [],          // custom eslint plugins
  envs: [],             // custom eslint environment
  parser: '',           // custom js parser (e.g. babel-eslint)
  usePackageJson: true, // use options from nearest package.json?
  useGitIgnore: true    // use file ignore patterns from .gitignore?
}

All options are optional, though some ESLint plugins require the filename option.

Additional options may be loaded from a package.json if it's found for the current working directory. See below for further details.

Returns a Promise resolving to the results or rejected with an Error.

The results object will contain the following properties:

const results = {
  results: [
    {
      filePath: '',
      messages: [
        { ruleId: '', message: '', line: 0, column: 0 }
      ],
      errorCount: 0,
      warningCount: 0,
      output: '' // fixed source code (only present with {fix: true} option)
    }
  ],
  errorCount: 0,
  warningCount: 0
}

async standard.lintFiles(files, [opts])

Lint the provided files globs. An opts object may be provided:

{
  // unique to lintFiles
  ignore: [],           // file globs to ignore (has sane defaults)

  // common to lintText and lintFiles
  cwd: '',              // current working directory (default: process.cwd())
  fix: false,           // automatically fix problems
  extensions: [],       // file extensions to lint (has sane defaults)
  globals: [],          // custom global variables to declare
  plugins: [],          // custom eslint plugins
  envs: [],             // custom eslint environment
  parser: '',           // custom js parser (e.g. babel-eslint)
  usePackageJson: true, // use options from nearest package.json?
  useGitIgnore: true    // use file ignore patterns from .gitignore?
}

Additional options may be loaded from a package.json if it's found for the current working directory. See below for further details.

Both ignore and files patterns are resolved relative to the current working directory.

Returns a Promise resolving to the results or rejected with an Error (same as above).

How do I contribute to StandardJS?

Contributions are welcome! Check out the issues or the PRs, and make your own if you want something that you don't see there.

Want to chat? Join contributors on Discord.

Here are some important packages in the standard ecosystem:

There are also many editor plugins, a list of npm packages that use standard, and an awesome list of packages in the standard ecosystem.

Security Policies and Procedures

The standard team and community take all security bugs in standard seriously. Please see our security policies and procedures document to learn how to report issues.

License

MIT. Copyright (c) Feross Aboukhadijeh.

standard's People

Contributors

asoul avatar bcomnes avatar caaatisgood avatar dcousens avatar dependabot[bot] avatar devjin0617 avatar effy-coding avatar falmar avatar feross avatar flet avatar greenkeeper[bot] avatar greenkeeperio-bot avatar honkinggoose avatar joshuacolvin avatar kohashi avatar linusu avatar max-mapper avatar mightyiam avatar munierujp avatar nachokai avatar ricardofbarros avatar richardlitt avatar rostislav-simonik avatar rstacruz avatar thclark avatar theoludwig avatar voxpelli avatar watson avatar wayou avatar yoga1234 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

standard's Issues

Add line ignore

Instead of:

/*eslint-disable no-unused-vars*/
var should = require('should')
/*eslint-enable no-unused-vars*/

Having:

var should = require('should') // eslint-ignore no-unused-vars

selectively disabling rules on a case-by-case basis. maybe.

Sometimes I do actually want ==. I can't think of any usecases now but I find that on occasion I explicitly opt for ==.

I'm wondering if some of these style restrictions could be selectively 'disabled' for a particular case if a comment is present to explain why an ill-advised practice was used instead of best practice.

"use strict"
var items = getCurrentItems()
// style: my religion speaks of a prophecy where vile, dark beings
// enter this realm and do unspeakable things to its inhabitants should 
// the chosen one (me, lol) fail to protect the semicolon of the 7th line of
// the 7th file. Remove this semicolon at your peril.
items = items.map(function(n) { return n * 2});
console.log(items)

maybe.

Support passing file names in as arguments

Run standard to recursively check a whole project.
Run standard < index.js to check an individual file.

Need to support: standard index.js or standard index.js test.js lib/a.js to check a list of files. Shouldn't be hard to add.

output is not shown when using through `watch`

Thanks for this.

I'm using it as such:

{
  "name": "foo",
  "devDependencies": {
    "watch": "^0.13.0",
    "standard": "*",
    "jasmine": "^2.2.0"
  },
  "scripts": {
    "watch": "watch 'npm test'",
    "test": "standard && jasmine"
}

When I run $ npm test all is well and as expected.

The issue comes when I use watch, such as $ ./node_modules/.bin/watch 'npm test' or $ npm run watch.

The output from standard is not printed. I know that standard runs because jasmine's output is printed.

Do you think that watch is doing something wrong?

Error: spawn ENOENT

I am on Windows 7 (64-bit) and did npm install standard -g and tried doing it.

I get this error:

c:\wamp\www\qtsite\src\js (master)
λ standard
Error: spawn ENOENT
    at errnoException (child_process.js:988:11)
    at Process.ChildProcess._handle.onexit (child_process.js:779:34)

Configuring external JSCS and ESLint

Continuing from #31, I don't think that a Vim plugin is the correct path to take.

We can leverage existing code to achieve more results if we aim to use the default behaviors of JSCS and ESLint.

JSCS can be directed to a configuration file through package.json.

So if we use the install npm script of standard to inject a property to direct JSCS to our config file, so that it ends up like the following

{
    "name": "some-package",
    "jscsConfig": "node_modules/standard/rc/.jscsrc"
}

Then JSCS will serve us, not matter if it is run through Vim or any other editor/tool, most likely.

Is this about JSCS correct, @mikesherov, please?
Would it prevent JSCS from processing other .jscsrc files in the tree?

ESLint seems halfway there, because it can be configured via package.json but it doesn't have an include directive.

Adding a property to the package.json seems reasonable to me, since our users will see that change and not miss it. And it will be documented and it is only a small change. We just have to figure out how well this works/will work with JSCS and ESLint.

This approach may even simplify Standard's code a little.

Syntastic has stopped working with [email protected]

Which makes me sad because now it seems like most of the ES6 stuff I use is handled properly. ;_;

I updated Syntactic to HEAD, and have verified that standard is working by running :!standard against an erroneous file from inside vim. If nothing obvious occurs to you about how the formatting might have changed in beta4, I can dig into this more tomorrow.

My opinion: Use of self is a bad idea

For a couple of reasons:

  1. self resolves to the global window context in the same way that this does, well at least that's been my experience and have been confused by it in the past. Open the dev console in chrome and eval self for an example.
  2. It assumes that there is only one item that will have it's context dissociated on callback firing. While this is generally true when you are writing nice clean code, there are occasionally instances where this will not be true.

Like I said though, this is just my opinion...

Use a single linter (eliminate jscs)

Using just a single linter would simplify standard, and even speed it up (#43).

eslint is excellent, and we've been slowly moving rules from jscs to eslint whenever possible. There are only a few rules that are unique to jscs at this point. The eslint project wants to support jscs options that make sense, so I think we'll be able to switch entirely very soon. These are the options we're waiting for:

if statements: force brace or one-liner

I find I have to double take when I look at this, to make sure I'm not mis-understanding what is actually part of the expressions that get executed.

The example is the following:

if (condition)
  expression
else
  more expressions
otherstuff

I think that is confusing and unnecessary, and IMHO it should only either be:

if (condition) expression
else more expressions

or

if (condition) {
  expression
} else {
  more expressions
}

edit: Infact, I only ever use the shorthand one-liner for early-exit return statements, but YMMV.

@feross thoughts?

web workers

the global variable in a web worker is named self, so renaming this to self in a worker can be tricky if you then need to grab a reference to the global, does this assume it's always in a browserify context?

Speed issues [enhancement]

First of all, I like the style of standard and I use it in all projects I started lately.

Buuuut, it always takes several seconds to test a single file in my test directory even if it only requires small files. My test file is about 150 LOC, the source is in this case even smaller.

Maybe this is an issue not with standard it self but with one of it's dependencies ... this is really interrupting my workflow.

[email protected]
Intel Core i5, 4 Gigs RAM, Ubuntu 14.04

Automatically set environment for common test frameworks

I use mocha, and standard complains about the undeclared variables (like describe, it, and before) that it uses. Of course, I can add

/*eslint-env mocha */

but that seems like something that could be handled by standard. Perhaps inspecting package.json to look at dependencies and directories.test, or just making some common guesses.

Perhaps this is outside of the scope, but it certainly would make me feel more standard if I could just arrange my projects in a specific way and ignore the linter directives entirely.

Errors in esformatter when using --format

standard --format
/usr/local/lib/node_modules/standard/node_modules/standard-format/node_modules/esformatter/node_modules/rocambole/node_modules/esprima/esprima.js:4118
            throw e;
                  ^
Error: Line 1439: Unexpected token else
    at createError (/usr/local/lib/node_modules/standard/node_modules/standard-format/node_modules/esformatter/node_modules/rocambole/node_modules/esprima/esprima.js:2030:21)
    at unexpectedTokenError (/usr/local/lib/node_modules/standard/node_modules/standard-format/node_modules/esformatter/node_modules/rocambole/node_modules/esprima/esprima.js:2099:13)
    at throwUnexpectedToken (/usr/local/lib/node_modules/standard/node_modules/standard-format/node_modules/esformatter/node_modules/rocambole/node_modules/esprima/esprima.js:2104:15)
    at consumeSemicolon (/usr/local/lib/node_modules/standard/node_modules/standard-format/node_modules/esformatter/node_modules/rocambole/node_modules/esprima/esprima.js:2216:13)
    at parseStatement (/usr/local/lib/node_modules/standard/node_modules/standard-format/node_modules/esformatter/node_modules/rocambole/node_modules/esprima/esprima.js:3628:9)
    at parseIfStatement (/usr/local/lib/node_modules/standard/node_modules/standard-format/node_modules/esformatter/node_modules/rocambole/node_modules/esprima/esprima.js:3114:22)
    at parseStatement (/usr/local/lib/node_modules/standard/node_modules/standard-format/node_modules/esformatter/node_modules/rocambole/node_modules/esprima/esprima.js:3591:24)
    at parseIfStatement (/usr/local/lib/node_modules/standard/node_modules/standard-format/node_modules/esformatter/node_modules/rocambole/node_modules/esprima/esprima.js:3118:25)
    at parseStatement (/usr/local/lib/node_modules/standard/node_modules/standard-format/node_modules/esformatter/node_modules/rocambole/node_modules/esprima/esprima.js:3591:24)
    at parseSourceElement (/usr/local/lib/node_modules/standard/node_modules/standard-format/node_modules/esformatter/node_modules/rocambole/node_modules/esprima/esprima.js:3881:24)

unnecessary semicolon

Consider this program:

var a = 1
if (a) {
  console.log('do something')
}

var b = 3
console.log(b)

;(function () {
  console.log('do another thing')
})()

Runs fine, no standard errors either.

Now consider this program:

var a = 1
if (a) {
  console.log('do something')
}

;(function () {
  console.log('do another thing')
})()

Runs fine, but standard prints the unnecessary semicolon error. While standard is indeed correct that the program and IIFE is fine without the semicolon prefix, the rule seems to be a bit too tight in this context. By default, I always prefix my IIFE with a ; so that I don't have to think of the contextual situations when it's necessary and when it is not. Do others do this? Is this a rule that should be relaxed? I'm guessing it's an eslint change.

Either way, this feels pretty low-priority to the other standard issues, but I thought that I'd bring it up for discussion.

Loving standard btw :)

Spaces for indentation?

I really like this forced standard! It's simple and will be effective. The only thing I can't get my head around is the 2 space indentation.

Why not use tabs instead? So that everyone in the team can configure their own horizontal depth?

JSX support

So, I'm trying to use standard on .jsx files. And I run into an issue where I can't use //jscs:disable and /* eslint-disable */, because they still depend on the AST parser and will throw an error if they can't parse the JSX templating.

Example file:

, render: function() {
    //jscs:disable
    /*eslint-disable */
    return <div className="form-horizontal">
      {this.renderTextInput('subject', 'Subject')}
      {this.props.email && this.renderTextInput('email', 'Email')}
      {this.renderTextInput('message', 'message')}
    </div>
  //jscs:enable
  /*eslint-enable */
  }

What do you think about this? I could potentially use fs.readFileSync(__dirname, '/form-template.jsx') and pipe the rendering jsx template through that, but that seems messy. Do you think there would be a way of using standard on these files, otherwise?

Support @jsx pragma

It's awesome that standard supports jsx now.

In addition to supporting React, babel supports generic JSX transforms, using a pragma like this:

/** @jsx mypackage.doSomething */

demo

Of course, when using them, standard is peppered with 'React' must be in scope when using JSX. Would it be possible to respect this pragma. It's not a Babel invention, React itself required it until recently.

Error: spawn E2BIG

Using [email protected] and [email protected]:

~/src/yw/finfin master*  7s
❯ npm t

> [email protected] test /Users/yoshuawuyts/src/yw/finfin
> standard && NODE_ENV=test node test | colortape

child_process.js:1132
    throw errnoException(err, 'spawn');
          ^
Error: spawn E2BIG
    at exports._errnoException (util.js:734:11)
    at ChildProcess.spawn (child_process.js:1132:11)
    at Object.exports.spawn (child_process.js:964:9)
    at spawn (/Users/yoshuawuyts/src/yw/finfin/node_modules/standard/index.js:
162:20)
    at /Users/yoshuawuyts/src/yw/finfin/node_modules/standard/node_modules/run
-parallel/index.js:32:7
    at Array.forEach (native)
    at module.exports (/Users/yoshuawuyts/src/yw/finfin/node_modules/standard/
node_modules/run-parallel/index.js:31:11)
    at /Users/yoshuawuyts/src/yw/finfin/node_modules/standard/index.js:136:7
    at done (/Users/yoshuawuyts/src/yw/finfin/node_modules/standard/node_modul
es/run-parallel/index.js:15:13)
    at /Users/yoshuawuyts/src/yw/finfin/node_modules/standard/index.js:157:7
npm ERR! Test failed.  See above for more details.

~/src/yw/finfin master*

Google doesn't seem to be familiar with these popping up in node. Maybe anyone's had this happen before? The project can be found here in case you want to replicate. Thanks!

Bug: ~/.eslintrc being taken into account for rules not defined in rc/.eslintrc

To reproduce, create a ~/.eslintrc file with this in it:

{
  "rules": {
    "no-var": 2
  }
}

Next, checkout the latest copy of standard and run npm test. You'll see many errors and the test will fail. This seems to be a feature of eslint: http://eslint.org/docs/configuring/#configuration-cascading-and-hierarchy

Note that this only affects rules that are not yet defined in rc/.eslintrc due to the layering/cascading nature. I see two possible solutions:

  • define every rule in rc/.eslintrc to stop the possibility of cascading
  • figure out a way to explicitly turn off the cascading feature when calling eslint.

Maybe @nzakas knows if there is a flag to stop this behavior? I did not see one in the command line options or on the linked configuration page.

The only workaround for users would be to remove any .eslintrc files from their directory hierarchy, which is probably not acceptable.

Exclude `coverage` directory

When I use istanbul in a project, it generates some js files in the coverage directory. This directory is in the Github-default .gitignore, and standard should probably ignore it by default too.

3.0.0-beta class support is wonky

bauchelain% standard --version
3.0.0-beta
bauchelain% standard
Error: Use JavaScript Standard Style (https://github.com/feross/standard)
  src/models/album-base.js:2:15: Missing space before function parentheses.
  src/models/album-multi.js:8:15: Missing space before function parentheses.
  src/models/album-multi.js:9:4: 'super' is not defined.
  src/models/album-multi.js:16:11: Missing space before function parentheses.
  src/models/album-multi.js:21:10: Missing space before function parentheses.
  src/models/album-multi.js:32:8: Missing space before function parentheses.
  src/models/album-multi.js:46:11: Missing space before function parentheses.
  src/models/album-single.js:4:15: Missing space before function parentheses.
  src/models/album-single.js:5:4: 'super' is not defined.
  src/models/album-single.js:15:11: Missing space before function parentheses.
  src/models/artist.js:2:15: Missing space before function parentheses.
  src/models/artist.js:8:18: Missing space before function parentheses.
  src/models/artist.js:12:11: Missing space before function parentheses.
  src/models/cover.js:4:15: Missing space before function parentheses.
  src/models/cover.js:12:11: Missing space before function parentheses.
  src/models/track.js:4:15: Missing space before function parentheses.
  src/models/track.js:20:11: Missing space before function parentheses.
  src/models/track.js:24:12: Missing space before function parentheses.
  src/models/track.js:32:12: Missing space before function parentheses.

As you can see, these are pretty standard uses of class syntax, and transpile without issue with babel. I haven't had the opportunity to dig in deeper and figure out what espree rules are causing these issues.

support app node_modules

we use the src/node_modules pattern in our apps (e.g. here and here), so the default ignore of **/node_modules/** doesn't work for us.

previous discussion in #35.

possible solutions already brought up:

  1. "we could ignore node_modules if a package.json is present in the same directory"
  2. implement a way to un-ignore a directory

1 makes a lot of sense, i don't see how it wouldn't work as the src/node_modules pattern as i understand it doesn't involve a src/package.json. keen to hear what people think, am happy to implement a PR for this.

eslint-plugin-react required?

its not clear why this module would be necessary, or why its not in the pre-req modules if it is necessary.

$ npm install standard
npm WARN prefer global [email protected] should be installed with -g
[email protected] node_modules/standard

$ ./node_modules/.bin/standard api.js 
Error: Use JavaScript Standard Style (https://github.com/feross/standard)

Unexpected Linter Output:
module.js:340
    throw err;
          ^
Error: Cannot find module 'eslint-plugin-react'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)

Make `--format` work with stdin

Currently, the --format flag only works when pointing at a file.

It should be updated to take input from stdin and send a formatted copy to stdout and send any lint errors to stderr.

Vim plugin

My VIM doesn't recognize that a project is Standard.

Is the presence of standard in package.json's devDependencies enough to flag that the package is Standard?

Perhaps both ESLint and JSCS should be patched to recognize the presence of Standard and then automatically look for the RC files in the right place?

Then, when used from within the editor, it just happens automagically—well, at least with some editors, who rely on external tools like that.

don't cross the browser and node streams

My best case against conflating the two modes is this incredibly silly change I had to make to npm to get the affected files through standard. I know that window.opener is a thing in browsers, but it has not been and never will be part of node, and this error message (like the one you get for crypto in some contexts) makes no sense unless you know / care about the browser-side problem it's trying to address.

I tried very hard to figure out how to remove / override the relevant global check via code comments, but either I don't understand how eslint applies those overrides, or it's simply not supported. Either way, I get that a lot of code will be browserified at some point and thus should pass the browser checks, but there is no plausible or reasonable reason to run npm in the browser (phrased that way because I know somebody probably is going to try anyway at some point). It should be OK for server-side apps to say "I am a server-only thing".

Remove undefined checks

This breaks on global variables, specifically mocha tests (it and describe). As mentioned here 91e8a41 your jshint checks are overzealous and defeat the purpose of this module, which states that it's for style checking.

Document/add programmatic use?

I'm trying to write some tests for standard-format and want to run standard against some strings inside the test. So far the CLI seems to be the only thing documented. It would be nice to have some documentation on how/what I can do once I require('standard'). I'll try to contribute some after I get my head wrapped around what is available and opening this issue in the meantime.

Fails to run

I've installed standard and tried to run it over my codebase, however it always seems to fail on this line:

/Users/jakechampion/.nvm/v0.10.28/lib/node_modules/standard/index.js:176
        var lineA = Number(LINE_RE.exec(a)[1])

I've tried installing standard locally to my project and as a global module, the issue is the same. When I had installed standard at version 2.3.1 in another project it didn't fail, so I imagine this issue has arisen between that version and the current one.

Below is a copy of my terminals output when installing and running standard on my project.

~/Projects/OfflineAudioOrg/OfflineAudio.github.io master*  11s
❯ npm i -g standard
/Users/jakechampion/.nvm/v0.10.28/bin/standard -> /Users/jakechampion/.nvm/v0.10.28/lib/node_modules/standard/bin/cmd.js
[email protected] /Users/jakechampion/.nvm/v0.10.28/lib/node_modules/standard
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected] ([email protected])
├── [email protected] ([email protected], [email protected], [email protected])
├── [email protected] ([email protected])
├── [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])
└── [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])

~/Projects/OfflineAudioOrg/OfflineAudio.github.io master*  14s
❯ standard
Error: Code style check failed:

/Users/jakechampion/.nvm/v0.10.28/lib/node_modules/standard/index.js:176
        var lineA = Number(LINE_RE.exec(a)[1])
                                          ^
TypeError: Cannot read property '1' of null
    at /Users/jakechampion/.nvm/v0.10.28/lib/node_modules/standard/index.js:176:43
    at Array.sort (native)
    at printErrors (/Users/jakechampion/.nvm/v0.10.28/lib/node_modules/standard/index.js:171:8)
    at /Users/jakechampion/.nvm/v0.10.28/lib/node_modules/standard/index.js:128:28
    at done (/Users/jakechampion/.nvm/v0.10.28/lib/node_modules/standard/node_modules/run-parallel/index.js:15:13)
    at ChildProcess.<anonymous> (/Users/jakechampion/.nvm/v0.10.28/lib/node_modules/standard/index.js:136:7)
    at ChildProcess.EventEmitter.emit (events.js:98:17)
    at maybeClose (child_process.js:753:16)
    at Socket.<anonymous> (child_process.js:966:11)
    at Socket.EventEmitter.emit (events.js:95:17)

ES6 support

I like standard; having gone through the exercise of converting what has to be one of the largest, most complicated code bases to support it so far, I find myself happy (or at least satisfied) with every choice it makes except the fact that it prescribes both the browser and node modes in eslint (for reasons I can get into in another issue, if desired).

But! I'm doing a lot more work with ES6 in my code now, and it would be nice to just go ahead and enable ES6 features as they roll into eslint (and jscs). It's probably going to be a little while before eslint supports everything (they just landed support for destructuring), but right now I have to keep switching between standard and eslint in my Syntastic configuration, and that feels suboptimal.

stdin support?

As I'm checking and porting my code, it's very convenient to do it piecemeal. Would you consider adding stdin support so that devs can do this:

standard < myfile.js

Like I said, it has the added bonus of making it much easier to port large codebases over. Thanks!

standard catching error in standard

This might have something to do with the installed toolset on my machine, but i tried running standard after installing globally (npm install -g standard), and I am getting an error thrown on what appears to the standard's index file.

➜  lib (master) standard
Error: Code style check failed:

/usr/local/lib/node_modules/standard/index.js:90
              var fileA = FILE_RE.exec(a)[1]
                                         ^
TypeError: Cannot read property '1' of null
    at /usr/local/lib/node_modules/standard/index.js:90:42
    at Array.sort (native)
    at /usr/local/lib/node_modules/standard/index.js:88:14
    at ChildProcess.<anonymous> (/usr/local/lib/node_modules/standard/index.js:133:21)
    at ChildProcess.emit (events.js:98:17)
    at maybeClose (child_process.js:756:16)
    at Socket.<anonymous> (child_process.js:969:11)
    at Socket.emit (events.js:95:17)
    at Pipe.close (net.js:465:12)

Have you seen this before, and/or know what the issue might be?

Expected a default case.

ex:

switch (typeof thing) {
  case 'function':
    return doSomething()
  case 'string':
    return doSomethingElse()
}

throw new TypeError('wtf did u just give me')

and i'd make those cases one-liners if i know none of the cases are going to be multiple lines

ignore: for projects that doesn't use package.json

Am using the standard command line tool from this project and am working on a Chrome project. Does that mean that I still need to use package.json and add the standard.ignore array? Or is there any generic way to ignore files?

Remove automatic stdin detection

People say it's a bad idea, i.e. hard to get right. I thought that browserify was making it work somehow, so thought we could make it work too, but @substack says it's not.

Let's just make the user explicitly pass - if they want stdin, like browserify does. This will probably fix the vim and syntastic issues we've been seeing: #65, #64

` character counted as space before closing parens?

Using the new ES6 syntax, I have several template strings passed as arguments to a function or method, formatted like this:

dothing(`url${variable}`)

Standard reports an error at the end of the line. The error text is:

Illegal space before closing round bracket

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.