• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Shopify/javascript: The home for all things JavaScript at Shopify.

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

Shopify/javascript

开源软件地址:

https://github.com/Shopify/javascript

开源编程语言:


开源软件介绍:

import JavaScript from 'Shopify'

Circle CI

This repository contains everything you should need for writing JavaScript at Shopify. In it you’ll find such things as our linting configs, custom linting rules, and project generators. Below, you’ll find the most important thing: a living styleguide documenting how and why we write JavaScript the way we do.

Why? All code in any code-base should look like a single person typed it, no matter how many people contributed. If we all follow along with the rules detailed below, we can focus our efforts on more meaningful problems.

Table of contents

  1. Using this guide
  2. Naming
  3. Punctuation
  4. Whitespace
  5. References
  6. Control flow
  7. Objects
  8. Arrays
  9. Strings
  10. Functions
  11. Types and casting
  12. ESNext features
  13. Project structure
  14. Resources

In addition to the above, we have created a specific guide for the tools and conventions surrounding JavaScript testing: our Testing styleguide. There are also a few additional guides for libraries commonly used at Shopify:

Have a legacy codebase? Can’t use ESNext? Our legacy styleguide is available in this repo just for you. We also have a dedicated CoffeeScript styleguide for projects that are still using CoffeeScript (new projects should use ESNext, though!).

Using this guide

Many of the following rules are enforced by our shared ESLint config/plugin, which you can use in most editors and CI environments. To use it, you will need to have Node.js >=5.7.0 and Yarn installed. As an alternative to Yarn, you can use npm which ships with Node.js.

Once these are installed, you must then install ESLint and the Shopify plugin:

With Yarn

yarn add --dev eslint eslint-plugin-shopify

With npm

npm install eslint eslint-plugin-shopify --save-dev

Once these are installed, you will need to add an ESLint configuration in your project’s package.json.

{
  "eslintConfig": {
    // or "plugin:shopify/es5" for the ES5 config, "plugin:shopify/react" for the React config.
    "extends": "plugin:shopify/esnext",
    // choose your environments: http://eslint.org/docs/user-guide/configuring.html#specifying-environments
    "env": {}
  }
}

Note: you can also provide an array of configurations, if you want to have linting rules for tools like lodash. See the eslint-plugin-shopify repo for details.

You can now use ESLint. The easiest way to do this is by adding a linting script to your package.json:

{
  "scripts": {
    "lint": "eslint . --max-warnings 0"
  }
}

And, finally, run your new script:

With Yarn

yarn run lint

With npm

npm run lint

Naming

  • 2.1 Use camelCase when naming functions, objects, and instances. Snake case is acceptable when interacting with an external API that provides objects with snake-cased keys, like Rails.

    ESLint rule: camelcase

    // bad
    const bad_snake_name = 'Larry';
    const BADname = 'this';
    const badObject = {some_prop: 'some-value'};
    
    // good
    const goodSnakeName = 'Basilisk';
    const prettyName = 'this';
    const goodObject = {someProp: 'some-value'};
    
    // not ideal, but sometimes necessary and acceptable
    const objectProvidedByRails = {some_rails_provided_prop: 'some-value'};
  • 2.2 Use PascalCase when naming classes, factories, enumerations, or singletons (cases of enums are written in screaming snake case).

    ESLint rule: new-cap

    // bad
    class badClass {}
    const bad = new badClass();
    
    const badType = {
      Water: 0,
      Fire: 1,
      Ghost: 2,
    };
    
    // good
    class GoodClass {}
    const good = new GoodClass();
    
    const Type = {
      WATER: 0,
      FIRE: 1,
      GHOST: 2,
    };
  • 2.3 Use a leading underscore when naming "private" properties. Functions and variables in scope should be named normally.

    Why? The leading underscore sends a signal to other developers that these methods should not be called or relied upon. Some tools can also obfuscate methods with leading underscores to ensure that they are not called by outside objects. Items in scope but not exported are completely private, so no signaling is required for these.

    Note: Use these underscore-prefixed members as a last resort. Prefer moving them to be functions/ variables in scope or making them part of the public API over using this naming convention.

    ESLint rule: no-underscore-dangle

    // bad
    export const bad = {
      __privateOne__: 0,
      privateTwo_: 1,
    };
    
    function _badPrivateFunctionInScope() {}
    
    // good
    export const good = {
      _private: 0,
    };
    
    function goodPrivateFunctionInScope() {}
  • 2.4 Avoid single letter names; be descriptive with the names you choose. Note that exceptions can be made for common one-letter identifiers, particularly for use as properties (x, y, i, j, _).

    ESLint rule: id-length

    // bad
    const b = 'BAD';
    
    // good
    const good = 'GOOD';
    const point = {
      x: 10,
      y: 20,
    };
  • 2.5 Don’t save references to this. Use an arrow function (preferred) or function#bind instead.

    // bad
    const badObject = {
      logSelfAfterTimeout() {
        const that = this;
        setTimeout(function() {
          console.log(that);
        }, 500);
      }
    }
    
    // better
    const betterObject = {
      logSelfAfterTimeout() {
        setTimeout(function() {
          console.log(this);
        }.bind(this), 500);
      }
    }
    
    // best
    const bestObject = {
      logSelfAfterTimeout() {
        setTimeout(() => console.log(this), 500);
      }
    }
  • 2.6 When naming an event object, use evt (as opposed to e or event).

    // bad
    function badHandleClickOne(e) {}
    function badHandleClickTwo(event) {}
    
    // good
    function goodHandleClick(evt) {}

↑ scrollTo('#table-of-contents')

Punctuation

  • 3.1 Always use semicolons.

    ESLint rules: semi and class-property-semi

    // bad
    function bad() {
      const badChoice = 'No semicolons'
      return badChoice
    }
    
    // good
    function good() {
      const goodChoice = 'Semicolons';
      return goodChoice;
    }
  • 3.2 Do not use leading commas.

    Why? It’s difficult to interpret and format, and trailing commas are a better solution to the same problems.

    ESLint rule: comma-style

    // bad
    const badOne = {
        one: 1
      , two: 2
      , three: 3
    };
    
    const badTwo = [
        1
      , 2
      , 3
    ];
    
    // good
    const goodOne = {
      one: 1,
      two: 2,
      three: 3,
    };
    
    const goodTwo = [
      1,
      2,
      3,
    ];
  • 3.3 Objects and arrays should use trailing commas, unless they are on a single line. Commas should always be followed by a space, but never preceded by one.

    Why? Trailing commas allow you to add and remove a given property of an object without also editing the surrounding lines, which keeps the change isolated to the property in question.

    Note: trailing commas are not permitted in JSON, so be sure to omit them.

    ESLint rules: comma-dangle, comma-spacing

    // bad
    const badOne = {
      foo: 1,
      bar: 2
    };
    
    const badTwo = {foo: 1, bar: 2,};
    
    const badThree = [
      1,
      2
    ];
    
    const badFour = [1,2];
    
    // good
    const good = {
      foo: 1,
      bar: 2,
    };
    
    const goodTwo = {foo: 1, bar: 2};
    
    const goodThree = [
      1,
      2,
    ];
    
    const goodFour = [1, 2];
  • 3.4 Never use commas to separate multiple statements.

    ESLint rule: no-sequences

    let a;
    
    // bad
    while (a = something(), a != null && a.length !== 0) {
      // do something
    }
    
    // good
    while (a = something()) {
      if (a.length === 0) { break; }
    }

↑ scrollTo('#table-of-contents')

Whitespace

  • 4.1 In general, add whitespace to improve legibility of code and to group statements together in a way that will produce a more coherent “story” for the next developer to look at code. Never optimize for code size: minifiers will do a much better job than you ever could.

  • 4.2 Use two spaces for indentation.

    ESLint rule: indent

    // bad
    function badOne() {
    ∙∙∙∙return true;
    }
    
    function badTwo() {
    ∙return true;
    }
    
    // good
    function good() {
    ∙∙return true;
    }
  • 4.3 Use braces for all blocks, including those that are on a single line.

    Why? Requiring braces prevents issues when a second statement is added to a single-line block.

    ESLint rule: curly

    const condition = true;
    
    // bad
    if (condition) doSomething();
    if (condition)
      doSomething();
      doSomethingElse(); // will run even if condition is false!
    
    // good
    if (condition) { doSomething(); }
    if (condition) {
      doSomething();
      doSomethingElse();
    }
  • 4.4 Place one space before a leading brace. When using if-else and try-catch constructs, the second part starts on the same line as the closing brace of the first, with a single space between them.

    ESLint rules: brace-style, space-before-blocks

    // bad
    function bad()
    {
      doSomething();
    }
    
    if (condition){ doSomething(); }
    
    if (otherCondition) {
      doSomething();
    }
    else {
      doSomethingElse();
    }
    
    // good
    function good() {
      doSomething();
    }
    
    if (condition) { doSomething(); }
    
    if (otherCondition) {
      doSomething();
    } else {
      doSomethingElse();
    }
  • 4.5 Place one space before the opening parenthesis in control statements (if, while, etc). Place no space between the function name and argument list in function calls and declarations.

    ESLint rule: keyword-spacing

    // bad
    if(condition) {
      doSomething ();
    }
    
    function doSomething () {}
    
    // good
    if (condition) {
      doSomething();
    }
    
    function doSomething() {}
  • 4.6 All operators should be surrounded by spaces.

    ESLint rule: space-infix-ops

    // bad
    const bad=34+32;
    
    // good
    const good = 1 + 2;
  • 4.7 End files with a single newline character. Avoid any end-of-line whitespace.

    ESLint rules: eol-last, no-trailing-spaces

    // bad-one.js
    const bad = true;
    // bad-two.js
    const bad = true;
    
    // bad-three.js
    const bad = true;∙∙↵
    // good.js
    const good = true;
  • 4.8 Use indentation when dealing with long method chains. Use a leading dot on each new line.

    Why? Breaking a method chain across lines improves readability. The leading dot clearly emphasizes that this is a method call, not a new statement.

    ESLint rules: dot-location, newline-per-chained-call

    const result = [1, 2, 3, 4, 5].filter((x) => x > 2).map((x) => x * x * x).reduce((total, x) => total + x, 0);
    
    // good
    const result = [1, 2, 3, 4, 5]
      .filter((x) => x > 2)
      .map((x) => x * x * x)
      .reduce((total, x) => total + x, 0);
  • 4.9 Do not include extra space inside parentheses, brackets, or curly braces that define an object literal. Include spaces for curly braces that define a single-line function.

    ESLint rules: space-in-parens, array-bracket-spacing, object-curly-spacing

    // bad
    function badFunction( arg ) {return true;}
    
    const badObject = { isBad: true };
    badObject[ 'isBad' ];
    
    const badArray = [ 1, 2, 3 ];
    
    // good
    function goodFunction(arg) { return true; }
    
    const goodObject = {isGood: true};
    goodObject['isGood'];
    
    const goodArray = [1, 2, 3];
  • 4.10 Limit the number of statements on a single line to improve readability.

    ESLint rule: max-statements-per-line

    // bad
    function bad() { dont = 'do this'; return please; }
    
    // good
    function good() {
      doThis = true;
      return thanks;
    }
    
    // fine as well, as long as there is only one, short statement.
    function fine() { return 'but don’t push it!'; }
  • 4.11 Line comments should appear above the line they are commenting, rather than at the end of the line or below it.

    Why? End-of-line comments can be harder to read since they lead to longer lines. Comments above the line you are documenting provides a more natural experience when reading the code, as it follows how we typically read other forms of text.

    ESLint rule: line-comment-position

↑ scrollTo('#table-of-contents')

References

  • 5.1 Always use let or const (as described in the following rule) to declare variables. Forgetting to do so will result in global variables, which is bad news.

    ESLint rule: no-undef

    // bad
    bad = BadChoice();
    
    // good
    const good = GoodChoice()
  • 5.2 Use const for all references that do not need to be re-assigned. Use let only for references that will be re-assigned. Never use var.

    Why? const and let are block scoped, rather than being function-scoped like var. const indicates that a given reference will always refer to the same object or primitive throughout the current scope, which makes code easier to reason about.

    ESLint rules: prefer-const, no-const-assign, no-var

    // bad
    var CONSTANT_VALUE = 1;
    var count = 0;
    if (true) {
      count += 1;
    }
    
    // good
    const someUnchangingReference = 1;
    let count = 0;
    if (true) {
      count += 1;
    }
  • 5.3 Initialize variables on declaration as often as possible. If a variable has no value until a later point (for example, it is calculated inside a complex conditional expression, or it is a variable in scope that is redeclared for each unit test), you can declare a variable without initialization.

    ESLint rule: init-declarations

    // bad
    let bad = null;
    // ...
    bad = 'bad';
    
    // good
    const goodOne = 'good';
    
    // or, if you can't provide a value immediately:
    let goodTwo;
    // ...
    goodTwo = 'good';
  • 5.4 don’t refer a reference before it is defined. The only exception to this rule is for functions; use the hoisting feature of functions liberally to allow the primary export of a file to appear first (and any helper or utility functions it uses to appear afterwards).

    ESLint rule: no-use-before-define

    // bad
    function bad() {
      return badVar;
    }
    
    const badVar = true;
    
    // good
    const goodVar = true;
    
    function good() {
      return goodVar;
    }
  • 5.5 Use screaming snake case for file-level constants to make it clear to users that they can’t be modified.

    // bad
    const constantValue = < 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap