Perspective of front end engineering Part 1: template function design

Wei 1 2020-11-13 06:33:07
perspective end engineering template function

1 Project template

Our project frameworks are generated based on project templates . Did you learn JS We know :

function Person(name = 'ant') { = name;
let man = new Person();

here Person yes man Prototype object . Again, a project template is equivalent to an object Person, The specific project is equivalent to man. Through the project template , We can define the functions we need in advance , When you use it, you just need to instantiate an object , simply new It's done in a second . Greatly reduce duplication of labor , The complexity of shielding project configuration .

Before we start building , It is necessary to have an overall plan for our project template , Then follow the plan one by one .

2 What functions are supported

2.1 Code checking

JavaScript It's a dynamic weakly typed language , It's easy to make mistakes in development . At the same time, because everyone's coding habits and styles are not the same , The style of code written is very different , It's hard to maintain over time . Because there is no compiler , JavaScript Code errors usually require constant debugging during execution , Efficiency is very low .

however , We can't do code checking with human flesh , Because when there is a lot of code today , It takes a lot of energy . So code checking we use ESLint To achieve .ESLint It allows programmers to find problems in the process of coding , Avoid bringing problems to execution .

Why use ESLint?

  • ESLint All of the rules are pluggable .ESLint No restrictions on the coding style of developers . It's designed to make the developers code their own style . Of course ESLint There is a set of built-in default rules . But you can modify or even customize your own rules. Everything is pluggable .
  • Each rule can be switched on and off freely . Developers can decide whether to open a rule according to the needs of their projects . You can also modify the alarm level of the inspection results , Decide whether to throw it wrong or just warn .

A simple example :

let foo = bar;
1:5 - 'foo' is assigned a value but never used. (no-unused-vars)

If we were ESLint The configuration file has enabled no-unused-vars The rules . So when there are variables in the code that are not used by definition , You'll get an error message .

as for CSS The inspection of , Here we use stylelint To deal with it .stylelint Very powerful , Can support scss、sass、less as well as sugarss The grammar check of . Besides ,stylelint and ESlint similar , It also provides a plug-in mechanism , Developers can define their own rules , Customize a unified set of specifications according to your own team , Avoid style errors .

Let's look at a simple example .

There's a passage like this css Code :

/* */
a { color: #FFF; }

stylelint The following rules :

"rules": {
"comment-no-empty": true,
"color-hex-case": "lower"

stylelint The content of the note cannot be empty , Font color 16 Base means that the letters are not allowed to be capitalized .

1:1 error Unexpected empty comment (comment-no-empty)
3:12 error Expected "#FFF" to be "#fff" (color-hex-case)

2.2 Local development environment

In daily development , Front end development is often done after the completion of part of the function and page development , Go and refresh the browser , Let's see if the effect is as expected . So there can be a local Web The server loads our page , And automatically refresh the page when the code changes , It can reduce the switching cost of development students , Improve development efficiency .

We use... In templates webpack-dev-server As A simple Web The server , because webpack-dev-server Built in module hot replacement (Hot Module Replacement or HMR), The page is automatically reloaded after being modified .

// package.json
"scripts": {
"dev": "webpack-dev-server --open"

stay Webpack Configuration file dev-server After configuration , All we need to do is package.json Add a script command . In development , Just a simple npm run dev Command to start the local server .

2.3 mock server

After the front and rear ends are separated , There are clear boundaries between the two sides , The back end is responsible for writing business logic , The front end is responsible for the development of view logic , Data transmission between the two parties is through API Realization . The front and back end agree on an interface document , The interface name is specified in the interface document 、 Enter the reference 、 Output parameters and data structure, etc .

But a static interface document is not enough , What we need is that in the development phase, we can call the server-side interface to get data just like online .

therefore ,Mock It is a necessary function in the front and rear separation mode .

The approach we take is to implement a mock server, To respond to local requests . At the same time, false data is passed through mockjs To generate .

Because of our local development environment and mock server Running on different ports , So we need to be in Webpack Provided in proxy Function to forward our request to mock server Up .

graph LR
A(dev server)-->B(proxy server)
B(proxy server)-->C(mock server)

2.4 structure

Now the front-end development is basically using the modular development method , And a lot of... Is used in the code es6+ Linguistic characteristics . But the support for new features in host browsers varies . Our code can't run directly in the browser , So you need to build and package the code , Compile the code into code that the browser can run .

// webpack.config.js
output: {
path: path.join(__dirname, './build'),
publicPath: opt.publicPath,
// Add... To resources in the online environment hash
filename: 'js/[name]' + hash(needHash, 'chunk') + '.js',
chunkFilename: 'js/[name]' + hash(needHash, 'chunk') + '.js',
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
// Delete console And warnings
drop_console: true,
warnings: false

Due to the different application scenarios of the object code , We need to build for different environments . such as , Code running against the test environment , Due to the need for continuous debugging , We don't usually clear comments and console. Since code deployment does not need to consider backup , Do not add hash. When building an online environment , We need to reduce the size of the file as much as possible , At the same time, we need to consider not covering online resources after deployment , So you need to eliminate comments and debug statements from your code at build time , Obfuscated compression of code , Add... To the file hash.

Most modern browsers now support native ES2015, Compiled packages are usually more than native ES2015+ The code will be more lengthy , Slower to run . So it's a waste to deliver bulky code to older browsers because they need to support them . We can make smaller packages for modern browsers in the template .

  • The modern version of the package is available in supported browsers through <script type="module"> Loading , Use <link rel="modulepreload"> Preload .
  • The old version of the package will pass <script nomodule> load , Support ES modules Your browser will ignore the reference .

2.5 Deploy

After building , The last step is to publish the front-end resources to the server . Let's assume that our front-end projects are completely front-end and front-end separated , This means that the front-end resources need to be deployed separately from the server side .

such as , We have a special OSS The server is used to deploy the portal file , Prepare another OSS Server deployment js、css And resources like pictures .

// package.json
"scripts": {
// Suppose our deployment logic is in deploy.js in
"deploy": "node deploy.js"

We'll use two for deployment npm package , One is vinyl-ftp, Specifically used to log in to our OSS The server , The other bag is vinyl-fs, It is used to publish local resources to remote servers . Finally, we package.json Configuration in file deploy command . The deployment operation only needs to be performed npm run deploy that will do .

2.6 Qdebug

I believe that in the process of testing , There is a problem that we often encounter . There are always test students to put some of the server-side bug To the front end . Front end students see bug after , Follow the recurrence steps to check ,“ Why ! This problem is caused by data problems in the interface !” Quickly transfer to the server students , And there's something wrong in my heart .

therefore , It is necessary to develop a small tool to help test students , Analyze for them bug Cause of occurrence , Assign exactly bug Provide factual evidence .

therefore , We need to implement one in the project template Qdebug Gadget .

// initialization
var debug = new QDebug();

Qdebug be based on vconsole Expand , The detailed interface data in the interface request can be printed out , At the same time, a version number of the current front-end code will be generated . Test students through the version number can know whether the front-end resources have been updated , By looking at the detailed interface data, you can accurately judge bug Attribution of .

2.7 automated testing

Automated testing at Web Play an important role in engineering . Automated testing can also be combined with continuous integration , The quality of the project is guaranteed by machines , Improve the overall effectiveness of the team . Therefore, in the process of front-end engineering construction , Automated testing is also an important part .

Automated testing depends on the granularity , Basically, it can be divided into : unit testing 、 The interface test 、 End to end testing ( It's also called functional testing ). Interface testing and end-to-end testing are mainly used in front-end engineering .

unit testing , From a developer's point of view , Divide the code into code units and test them one by one , To see if the results are in line with expectations .

We go through Karma+Mocha+Chai To implement unit testing function . It's easy to perform unit tests and pass npm script To call , for example :

npm run test:uinit

End to end testing is from the user's point of view , hold Web Application as a black box , Simulate the user's real use scenarios , For example, enter text on the page , Click on the search . See if the test results are in line with expectations . There are many end-to-end testing frameworks , such as Nightwatch、TestCafe、CasperJS. In this template , We chose to use Nightwatch To implement end-to-end testing , Mainly because of the use of Nigthwatch The code is very simple .

Performing an end-to-end test is easy to pass npm script To call , for example :

npm run test:e2e

3 Directory structure

After finishing the main functions of the template , Let's take a look at the overall directory structure of project templates :

├── package.json
├── .gitignore
├── .babelrc
├── config
├── build
├── mock
├── test
| ├── unit
| └── e2e
├── src
| ├── assets
│ ├── components
│ ├── router
│ ├── pages
│ ├── app.js
│ └── App.vue
└── public
├── index.html
└── favicon.ico

Some of the main directory and file functions are as follows :

  • src Store business code in . among src/app.js It's the entry file for project construction ,src/App.vue It is the entry file of the view layer ,src/pages Put different pages in ,src/components In the place Vue Components ,src/router In the place router Related documents ,src/assets Place static resources such as pictures in 、 Font, etc. .
  • mock Deposit Mock False data of .
  • test Used to place test related files .
  • build Used to place build related files .
  • config Used to place configuration related files .
  • public Used to place common static resources , Such as HTML Entry template file 、 The small icon of the site .
  • package.json npm The configuration file for the module .
  • .babelrc babel Configuration file for .
  • .gitignore Used to specify which files are not submitted to Git Warehouse .
  • Project introduction and usage document .


In this section, we systematically plan and design the directory structure of the template function . Template functionality covers the development phase 、 Testing phase 、 Construction phase 、 Deployment phase . This paper also gives a brief introduction to the technology and tools needed for the realization of each function , You can have a general impression of each part , After that, we can strengthen the practice in practice .

The author has a front-end engineering practical course just launched ——《 Perspective front end Engineering 》.

Click to learn about 《 Perspective front end Engineering 》.

With Vue For example , Combined with the author's engineering practice in the team , Lead you to build a scaffold from scratch , Dismantle the technical points used in scaffold construction one by one , I hope you'll see , Everyone has a deep understanding of scaffolding and engineering ideas .

The course catalog

Opening words : What is front-end engineering

The first part : Formwork design

The first 01 course : Template function design
The first 02 course :Webpack Basic introduction
The first 03 course : Build project template framework
The first 04 course : Front end modular solutions
The first 05 course : Building local development environment
The first 06 course : Build local Mock service
The first 07 course : Introduce code checking tools
The first 08 course : Automatically generate sprite map
The first 09 course : Build from the browser
The first 10 course : Build on the environment
The first 11 course : Integrated mobile debugging tools
The first 12 course : Introduce unit testing
The first 13 course : introduce e2e test
The first 14 course :Webpack Build performance optimization
The first 15 course : Add deployment capabilities
The first 16 course : Aggregate project configuration and template

The second part : Command line design

The first 17 course :cli Functional design ( On )
The first 18 course :cli Functional design ( Next )

Conclusion : An open mind is a higher level of engineering

I believe that after finishing this course , We have at least the following gains :

  • Have a systematic understanding of front end engineering ;
  • Can independently design a set of front-end engineering solutions ;
  • The breadth of knowledge has been greatly improved ;
  • Into a better platform , Get better pay .

interested , I hope you will support me a lot !

Author's brief introduction :

Wang Chao , Now fast Dog Taxi ( primary 58 Express ) Head of front end .

I have worked in Renren 、 qihoo 360,8 Years of working experience in the Internet .

from 0 To 1 Set up a fastdog front-end team , Responsible for the construction of team technical system , In the order Webpack and Vue Based on 、 Node.js The middle layer is complementary , automation 、 engineering 、 Component based fastdog front end technology system .

本文为[Wei 1]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple