preface

As time goes on, the front-end development more and more complex, technology stack is also emerge in endlessly, all kinds of engineering, modularization has become the front development path, in order to better solidarity and collaboration, open extension, after-sales service, the company also has a unique development rules, here, I will share our front end code development specification

As our company mainly uses Vue technology stack, we will take Vue technology stack as an example and share it mainly from the following points

  • Use the Ts + ESLint specification
  • Project directory structure
  • Component naming conventions
  • Routing naming convention
  • Event, method naming conventions
  • Naming conventions for variables and constants
  • Annotation specifications

Holistic structure paradigm

my-project-demo    // Project directory
-- node_modules    // Dependency file
-- public          // Static resource entry index.html
-- src             // Core working directory
    -- assets      // Static resource directory
        -- icon
        -- imgs
        -- less  
    -- components  // Component directory
    
        -- base-comps  // Base component directory
            -- base-button  // Component directory
                -- base-button.less
                -- base-button.tsx | .ts
                -- BaseButton.vue
            -- index.ts // unified entry processing, format
            
        -- custom-comps // Business component directory
            -- todo-list
                -- todo-list-item // Tightly coupled components directory
                    -- todo-list-item.less
                    -- todo-list-item.tsx | ts
                    -- TodoListItem.vue
                -- todo-list.less
                -- todo-list.tsx | ts
                -- Todo-list.vue
            --index.ts  // unified entry processing, format
                
        -- mixins-comps // use the same logic
            -- demo-mixin.ts
            -- DemoMixin.vue
            
    -- router      / / routing
        -- index.ts
        
    -- store       // State management
        -- index.ts
        -- module-a.ts
        -- module-b.ts
        
    -- utils       / / tools
        -- global.ts
        
    -- views       // Main view directory
        -- Home.vue
        -- About.vue
        
    -- App.vue     // Vue core entry file
    -- main.ts     // ts core entry file
    -- shims-tsx.d.ts // Support TSX configuration
    -- shims-vue-d.ts // Support vUE to use ts
-- .browserslistrc / / the browser
-- .eslintrs.js    / / eslint specification
-- .gitigonre      // git
-- babel.config.js // Babel configuration file
-- package.json    // Dependency management, project startup and package command configuration files
-- REDEME.md       // Documentation
-- tsconfig.json   // ts configuration file
-- vue.config.js   // Webpack configuration file


Copy the code

Project directory structure

Based on the above example, you can see more or less what it looks like. Here are just a few descriptions

  • Component directory must be subdivided into basic components and business component directory, because basic components are generally used as the basic control of the project, will be highly encapsulated by abstraction, through different configurations, to achieve different effects, while business components are only needed in the current project. In the reference exampleBase-comps custom-comps mixins-comps directory
  • It is recommended to have an index.ts file in each directory as far as possible, which can be exported as needed. Even if it is not necessary, an empty file should be created to keep the project structure
  • Tightly coupled components must present a tree level directory that is nearby for easy management and lookup
  • Each component has a separate directory with its own style files and component files, which can be relied on nearby for later maintenance
  • If Vuex status management is used frequently, try to differentiate multiple modules to achieve regional status management

Component naming conventions

  • Components are divided into basic components and business components
  • Components are divided into three forms:.vue.tsx. ts

The base component starts with base, and the business component starts with custom, which means to customize the business component. Then the component has three file forms. The vue suffix is generally capitated + hump, while the TS and TSX suffix are all separated by small letters, separated by –

Ex. :

compoents
   MyButton.vue // vue suffix, uppercase + hump
   base-comps
       base-button
           base-button.tsx | ts // ts or TSX suffix
Copy the code

Style files are named the same way

Routing naming convention

Route names are all lowercase and words are separated by – because if you use underscores or humps, they are treated as one word, search engines can’t distinguish semantics, and – is more intuitive and beautiful

Ex. :

const routes: Array<RouteConfig> = [
  {
    path: '/'.name: 'Home'.component: Home
  },
  {
    path: '/about-us'.// Use the - separation, which will be resolved to about and US more easily identified by search engines
    name: 'About'.component: () = > import(/* webpackChunkName: "about" */ '.. /views/About.vue')}]Copy the code

Event, method naming conventions

The event names here usually refer to the event names and listeners broadcast through $emit, while the methods are custom method names

  • $emit eventName usually uses on + “-” + eventName

  • Custom methods can be divided into many types. Generally, handle prefix is used. For some judgment methods, including method, obtaining value and setting value, they have their own prefixes, which adopt prefix +Event time name and camel name

  • Handle most custom method prefixes

  • Whether has contains a value method prefix

  • Whether is is a value

  • Get Gets a value

  • Set Sets a value

Ex. :

/ / the parent component
<div @on-emit-evet="handleEmitEvent"
     @click="handleClick"> method triggers </div>// parent ts script (method naming example)
handleClick (): void {}
handleEmitEvent (arg): void { console.log(arg) }

isPhone (): boolean {return false}
hasLoactionString (): boolean {return false}
getCountValue (): number {return this.count}
setCountValue (n:number): number { this.count = n} 


/ / the child component
<div @click="handleClickEmit"> Event trigger </div>// child-ts script
@Emit("on-emit-event")
handleOnEmitEvent():string{
    return "Parameters"
}
Copy the code

Here, incidentally, public methods naming conventions, especially make tool platform for secondary development implementation to use, how to block public method named conflict, the solution, of course, there are many, the wrapper class, mounted to the global object object naming need special treatment, etc., can be, if it is directly define global method, you need to certain specification can to avoid this problem, Here’s how I did it

Custom unique value + Common + method name, camel name

This unique value, which can be discussed and decided on its own, is more optimistic if it fits into the current product or has relevance to the company

Ex. :

function NtCommonThousandth (n: number) :number { return n }
Copy the code

Naming conventions for variables and constants

  • Variables are generally declared with let, camel name format, semantic
  • Constants are separated by uppercase letters and underscores

Ex. :

let homeTitle: string = "Home page title"
constMAX_SCREEN_VALUE: number =1920
Copy the code

Annotation specifications

My favorite annotation specification is the JSDoc specification, which also applies to TS/TSX

<script>
    
    // Url declaration field, single line comment
    let url = "http://www.baidu.com"
    
   / * * * @ encoding time | | operation description * *@return(indicates a return value) {return type} *@param (parameters)} {parameter type | | variable name parameters description * * /
    
    
    / * * *@Hs 2021.11.15 * Get the URL value *@return {string} * * /
    function getUrl () :string { return url}
    
    / * * *@Hs 2021.8.15 * Sets the URL value *@param {string} U New URL value * *@XXX 2021.11.15 optimization | * describe... Same structure as above **/
    function setUrl (u:string) :void {
        url = u
    }
    
</script>

Copy the code

Everyone has his own coding habits. Of course, it is better to restrict it. At least according to this structure, the overall effect will not be too bad, but also convenient for colleagues to check and maintain, and the code will look a lot orderly. Ok, that’s all for today’s sharing.

A little encouragement, great growth, welcome to like collection