I thought I was proficient in Vue, but I didn't expect to be abused by the former Ali boss...

Preface

It's the golden job hunting season again. I am a front-end rookie who has been in the industry for more than a year. Last summer, I started thinking about changing jobs and interviewed several small and medium-sized companies. I usually record the interview process so that I can review it after the interview. I have sorted out the notes of several interview review, and I hope it will be helpful to friends in similar situations "it is also convenient for me to recall later". I hope everyone can find a job they like.

Overview

  • Company: Coordinates Shanghai, education industry, front-end team with 20+ people.
  • Interviewer: Front-end person in charge, former Ali P7 boss, graduated with a master's degree and transferred to Ali.
  • Technology stack: The team currently mainly uses vue, and plans to use react in the future.
  • Interview result: failed o(╥﹏╥)o.
  • Interview feelings: The interviewer is kind, and will be moderately guided when encountering problems that he won't know. Finally, he also gave suggestions for improvement. I feel that I have gained a lot. Obviously being abused terribly, but still very happy.

Interview questions

Note: The number at the end of the question represents the scoring of your answer at that time, ✔ means that there is a rearrangement of the question later.

  1. Reason for change
  2. What is the difference between vue and react? 2 ✔
  3. The principle of vue two-way data binding? Update of the array. 8 ✔
  4. How is the communication between components? How does vuex work? How does the state change cause the view to change? 6 ✔
  5. Why choose uni-app? 8
  6. (After searching and viewing the e-commerce applet) What parts did you do? For image loading problems, why not use intersection observer in horizontal direction? Intersection Observer comes with the browser. 7 ✔
  7. Why do you want to make a live plug-in? 8
  8. What project optimizations have you done? 5 ✔
  9. The difference between webpack configuration, loader and plugin. How to remove redundant code? The principle of tree-shaking. 5 ✔
  10. How does a new route know to download the corresponding file? (Extension: the way of dynamically inserting js) 2 ✔
  11. On-demand loading? What are the ways? What did you choose in the end? 5
  12. Cache, who set up strong cache? Will html files be cached? 4 ✔
  13. cdn content distribution system? Why are the static resource files of your project not on the CDN. 5 ✔
  14. What are the difficulties when using Tencent Cloud's mobile live broadcast and instant messaging SDK? 4 ✔
  15. Sentry error monitoring, how are errors collected and reported to the platform? (Http, websoket, cross-domain) 2 ✔
  16. XX project (in the resume), explain in detail? 8
  17. Difficulties and challenges encountered in the project. 4

Question 2 Vue vs React

Same point:

  1. Use virtual DOM + Diff algorithm.
  2. Componentized thinking.

difference:

  1. The template syntax is different: react renders templates through JSX, and vue renders through extended html syntax. For example, in React, interpolation, conditions, and loops are all implemented through JS syntax, and Vue is implemented through instructions v-bind, v-if, and v-for.
  2. The principle of monitoring data changes is different: Vue uses getter and setter hijacking to notify data changes, and react uses comparison references. Responsive data used by vue, while react is immutable data. Vue changes the data directly and assigns it directly. React needs to call the setState method (replace the old state with the new state).

Question 3 Vue responsive principle

level1: In vue2.0, the core of the responsive implementation is ES5's Object.defineProperty(obj, prop, descriptor). Through Object.defineProperty(), the getter and setter of each property of data and props are hijacked. The getter does dependency collection, and the setter distributes Update. Overall it is a data hijacking + publish-subscriber model.

level2: Specifically, ① Vue initialization phase (after beforeCreate before create), traverse data/props, call Object.defineProperty to add getter and setter to each property. ② Each component and each computed will instantiate a watcher (of course, including each custom watcher), and subscribe to the data/props/computed used for rendering/calculation. Once the data changes, the setter will be called and the rendering will be notified The watcher recalculates and updates the components.

Question 4 vue component communication

level1 : props+events parent-child component communication (parent/parent/parent/children), vuex any component communication, event center emit/emit / emit/on any component communication, attrs/attrs/attrs/listeners descendant communication (provide / inject ).

level2: vuex operating mechanism: the state of vuex acts as a warehouse, providing data-driven vue component rendering. The view dispatches actions through dispach, and some asynchronous operations can be done in actions. Actions or views are submitted to mutations through commit, and mutations change the state.

level3: Source code analysis: Vuex is actually a Vue.js plug-in. Plug-ins need to provide an install method. The install method call will pass in Vue as a parameter. Vue.user (plugin) installs the plug-in, that is, executes the install method of the plug-in. A beforeCreate hook function will be mixed globally to save the instantiated Store to this.$store of all components.

level4: The mutation changes the state, what will trigger the view change? Realized by vue, [Instantiate vue, use state as a data attribute. ] ↔️ core

let Vue
function install(_Vue) {
  Vue = _Vue
  function vuexInit() {
    const options = this.$options
    console.log('vuexInit -> this.$options', this.$options)
    if (options.store) {
			// // 根实例 this --> Vue
      this.$store =
        typeof options.store === 'function' ? options.store() : options.store
    } else if (options.parent && options.parent.$store) {
			// 组件实例 this --> VueComponent, 如 APP, Home, About...
      this.$store = options.parent.$store
    }
  }
  Vue.mixin({ beforeCreate: vuexInit })
}

class Store {
  constructor(options = {}) {
    const { state = {}, mutations = {}, getters = {} } = options
    this._mutations = mutations
    // getter实现原理
    const computed = {}
    this.getters = {}
    for (let [key, fn] of Object.entries(getters)) {
      computed[key] = () => fn(this.state)
      Object.defineProperty(this.getters, key, {
        get: () => this._vm[key]
      })
    }
    this._vm = new Vue({
      data: { $$state: state }, // 核心原理
      computed
    })
  }

  commit(type, payload) {
    if (this._mutations[type]) {
      this._mutations[type](this.state, payload)
    }
  }

  get state() {
    return this._vm._data.$$state
  }
}

export default { Store, install }

Question 6 Intersection Observer

level1: Infer whether the node is visible to the user, and what proportion is visible, cross the observer. There is also in web API.

level2: The IntersectionObserver in the applet is encapsulated on the basis of the Web, and returns an IntersectionObserver instance through createIntersectionObserver. Instance methods include relativeTo, relativeToViewPort, observer, disconnect. relativeTo and relativeToViewPort are relative to the specified position of the specified element or viewport. observer(selector, cb), which observes the specified node and triggers a callback when the visibility changes.

level3: Web API, new IntersectionObserver(cb, options). The configuration of root and rootMargin in options can achieve the effects of the relativeTo and relativeToViewPort methods in the applet. In addition, the thresholds attribute is also quite interesting, triggering a callback when a few intersecting ratios are specified.

Question 8 Project optimization

  1. Remove the console printing in the production environment. There are many solutions, esling+pre-commit, automatic removal using plug-ins, plug-ins include babel-plugin-transform-remove-console, uglifyjs-webpack-plugin, terser-webpack-plugin. Finally, I chose terser-webpack-plugin. Scaffolding vue-cli uses this plugin to enable caching and multi-threaded packaging. There is no need to install additional plugins. Just set the drop_console of the terser plugin to true in configureWebpack. It is best to develop good coding habits and remove the useless console after the development is basically completed. The turbo console in vscode is just fine.
  2. On-demand loading of third-party libraries. echarts, the official document uses the module specified by the configuration file, and the other uses babel-plugin-equire to achieve on-demand loading. element-ui uses babel-plugin-component to implement on-demand introduction.
  3. Public styles, such as uniform adjustments to the styles of some element-ui components (such as pop-up boxes, tables, drop-down selection boxes, etc.). Common components, such as date-picker, upload-file, etc., are basically further encapsulated in the components provided by element-ui. Custom components include preview-file, search box, etc.
// babel.config.js配置如下:
plugins: ['equire']
// echarts.js
const echarts = equire(['line', 'tooltip', 'legend', 'dataZoom', 'grid']);
export default echarts;

In terms of front-end and back-end data exchange, promote the project team to use Blue Lake and interface documents, negotiate with back-end classmates, and standardize the back-end data return.

As mentioned in the Yahoo Military Regulations, avoid css expressions, filters, less DOM operations, optimize pictures, sprites, and avoid empty links in pictures.

Performance issues: page loading performance, animation performance, operation performance. Performance API, record performance data.

Winter relearns front-end optimization technical solutions:

  1. Caching: A strong caching strategy controlled by the client.
  2. Reduce request cost: DNS is controlled by the client, and it actively requests to obtain the domain name IP at regular intervals, instead of using the system DNS (it is completely unintelligible). TCP/TLS connection reuse, server upgrade to HTTP2, try to merge domain names.
  3. Reduce the number of requests: JS and CSS are packaged into HTML. JS controls the asynchronous and lazy loading of pictures. Use data-uri for small images.
  4. Less transfer volume: Try to use SVG\gradient instead of pictures. Control the picture clarity according to the model and network conditions. Use sharpening for low-resolution images to enhance the experience. Avoid large background images in design.

问题9 loader、plugin、tree shaking

loader

Convert the source code of the module, convert different languages ​​to JS, or convert inline images to data urls. Such as: file, url-loader, file-loader. Conversion and compilation, babel-loader, ts-loader. Template, html-loader. Style, style-loader, css-loader, less-loader. Clean up, eslint-loader. Framework, vue-loader.

plugin

Solve other things that loader cannot achieve. Such as HtmlWebpackPlugin, CleanWebpackPlugin, webpack-bundle-analyzer, DllPlugin, HotModuleReplacementPlugin.

tree shaking

Eliminate useless js code (remove parts that are not exported or referenced in the module). Only the static import method of ES Module is supported, and the dynamic import method during require runtime is not supported.

The introduction of ES6 modules is statically analyzed, so you can correctly determine which code to load at compile time.

The content that can be eliminated is limited . Webpack cooperates with uglifyJS to package files and can only shake part of the code, such as the side effects of module code , immediate execution of functions, etc., can not be shaken. uglifyJS does not perform program flow analysis, but simply judges whether the variable is subsequently referenced or modified, and does not exclude code that may have side effects. (Rollup will) Also, for example, router.js in the project references page components, but they are not used in routing rendering and cannot be shaken.

webpack-deep-scope-analysis-plugin: Use webpack to analyze the AST of the module, use the scoped analysis tool to analyze the reference relationship, and exclude the unused modules.

1. babel.config.js 配置,分析文件模块依赖关系,生成AST时,保持ES6不动。
{
	"presets": [ ["env", { "modules": false }] ]
}

2.  方式1,import {Button} from 'antd'; 
    方式2,import {Buttion} from 'antd/lib/button';
           import 'antd/lib/style';
这两种方式,tree-shaking效果差别很大。(副作用范围不同)
babel-plugin-import-fix 插件,遍历AST找出类似import {Button} from 'antd'的结构,进行转换重新生成代码。

3. CSS tree-shaking <https://juejin.im/post/6844903808397475847>
  方式1:mini-css-extract-plugin + purifycss-webpack
	方式2:webpack-css-treeshaking-plugin。
	利用postCSS提供的解析器,将CSS解析成AST,遍历获取选择器与js、html代码匹配,删除匹配不到的,返回AST,重新生成代码。

Question 10 lazy loading routing

Test site, the realization principle of vue-router.

level1:

  1. Pack the sub-modules that need to be lazily loaded into separate files. ES6's import().
  2. During hashChange, a specific function is executed according to the hash change, and sub-modules are loaded.

level2: Three ways to implement, location.hash + hashChange(), pushState (IE10) + popState event monitoring of HTML5 specification, abstract nodejs default value.

**level3: **Source code analysis. Route installation, use mixin to inject beforeCreated and destroy hook functions into each component, define route and route, route and router on the Vue prototype, and perform responsive processing, and define global rotor-link and router-view components. Create a mapping relationship based on the routing configuration. A new path is calculated according to the incoming path. During the switching process of Road King, a series of navigation guard functions are executed, Url is changed, and corresponding components are rendered.

Question 12 Caching

html files will also be cached. Index.php is used in the project, and the backend returns html content, which will not be cached.

Browser caching strategy:

  • Mandatory cache: (within the specified time, the browser directly uses the strongly cached content)

    Expires:Thu.21 Jan 2019 23:59:59 GMT; (HTTP1.0)

    Cache-Control : max-age=3600 (HTTP1.1, higher priority)

    [Caching instructions: no-cache needs to negotiate the cache to verify whether it is expired; no-store does not cache; public client proxy servers can cache; private clients can cache]

  • Negotiation cache: (negotiate with the server to determine whether the resource is updated)

    Last-Modified (server delivery time): Thu.21 Jan 2018 23:59:59 GMT; (HTTP1.0)

    If-Modified-Since (Browser inquiry) [Maybe the time has changed, the content has not changed]

    Etag (issued by the server); (HTTP1.1)

    If-None-Match (Browser inquiry)

Question 13 CDN

CDN, content distribution network, is a virtual distributed network based on a rebearer network, which can cache source site content on node servers across the country or around the world. Users get the content nearby, which improves the access speed of resources and shares the pressure of the source station.

Use DNS domain name resolution to guide users to access the cache server.

Question 14 Difficulties of Tencent Cloud SDK

Encapsulate the IM class, define the creation of SDK instance on the IM class, log in/out, join/exit groups, monitor and remove IM events.

  1. Mobile live streaming SDK. In the beginning, I didn't do the anchor end of the small program, and used the APP to push the stream. Mainly do the content of PC and H5 streaming.
  2. There are several types of live broadcast protocols...
  3. The HLS protocol used at the beginning uses TC-Player provided by Tencent Cloud as the player. The problem encountered, the delay is high.
  4. Consider changing the protocol, but the mobile browser does not support flv and rtmp.
  5. Tencent Cloud provides the TC-Player plug-in for streaming on the web. TC-Player essentially uses the video tag that comes with the browser.
  6. Use flv as the live broadcast protocol, but not directly use the flv format to play. There are two solutions on github, one is bilibili flv.js, which transcodes and multiplexes flv file streams into MPE casually, and realizes video playback through Media Source Extensions API. Another solution is to draw each frame of the video using CANVAS.

Question 15 sentry

The sentry error log is sent to sentry's web site via https. Use cors to achieve cross-domain.

  1. Application (Sentry Client SDK) Messages are reported to the web
  2. Put message processing into message queue (Redis/Rabbitmq)
  3. Worker fetches data from the message queue for processing
  4. Finally, postgresql completes the message storage
**request headers:**
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross site
**response headers:**
access-control-allow-origin: <http://localhost:8080>
access-control-expose-headers: x-sentry-error, retry-after, x-sentry-rate-limits

After being abused in the interview, I started to brush up on the interview questions and sorted them out and shared them with everyone for free, hoping to bring good luck.

Due to limited space, only part of the interview questions can be shared, and more interview questions and answers can be read and downloaded by [click me] ~ Share it with everyone for free, it is a thankful feedback.

Guess you like

Origin blog.csdn.net/hugo233/article/details/114853078