The employment situation this year is simply dark. Based on the "lucky mentality" that next year will be worse than this year, I chose to resign without hesitation. After a month and a half of hard work, I received a pretty good offer. The salary and platform have been greatly improved, but there is still a big gap with my psychological expectations. So the biggest conclusion is: don’t talk naked! Don't say anything naked! Don't say anything naked! Because the pressure brought to people during the interview and the psychological damage caused by the gap between reality and ideals are immeasurable, it is a good choice to survive in such an environment.
Related recommendations:Summary of 2023 front-end interview questions (collection)
Next, we will summarize the following things that will be experienced in front-end interviews under normal circumstances. Four stages and three determining factors:
As a front-end staff, the depth and breadth of technology is ranked first. Three years is a dividing line. You must find your own right at this time. Orientation and direction.
Secondly, good communication and expression skills, clothing and performance and other off-site factors can increase the interviewer's recognition of you.
Some people are very skilled, but the interviewer feels uncomfortable during the interview. They think you are arrogant/sloppy/self-righteous/cannot express themselves clearly, so they will just reject you. That is the worst loss.
The following is a summary of my entire interview preparation and the questions I was asked, because during the interview process, the communication with the interviewer is not a simple endorsement to a large extent. It is best to pass the knowledge Express your own summary and conciseness, and then supplement and improve it on the spot based on the interviewer's questions. [Recommended learning:web front-end,programming teaching]
The interviewer will ask you to introduce yourself , and does not limit the scope of self-introduction. The interviewer must want to know you from your self-introduction, so the introduction must be brief and smooth. Facing different interviewers, the content of self-introduction can be exactly the same. Therefore, it is important to prepare your words in advance, and be sure to pay attention: don’t stumble, be confident!Smooth expression and communication skillsis also one of the interviewer’s assessment points for candidates. I have also been an interviewer. Candidates who are confident and generous are often more likely to be favored.
1. Personal introduction (basic situation) and main resume are all available, which must be short
2. What you are good at, including technical and non-technical. Technical people can understand your transition, and non-technical people can understand you as a person
3. Pick the most core projects of the projects you have done, and don’t introduce all the projects like endorsements
4. Some of your own ideas, interests or opinions, even your own career plans. If this gives the interviewer a feeling: keen on "tossing" or "thinking"
Example:
Hello interviewer, my name is xxx, I graduated from xx University in xx. Since graduation, I have been engaged in front-end development related work.
The technology stack I am good at is vue family bucket, and I have a certain degree of research on the use and source code of vue2 and vue3; the packaging tools are familiar with webpack and vite; I have dominated medium and large-scale projects from zero to one Experience and ability in project implementation.
In my previous company, I was mainly the person in charge of the xx product line, and my main responsibilities were. . . . . .
In addition to development-related work, he also has certain technical management experience: such as serving as a requirement review, UI/UE interaction review judge, responsible for development scheduling, member collaboration, reviewing member code, organizing regular meetings, etc.
I usually record some learning articles or study notes on the blog I built, and also write some original technical articles and publish them on the Nuggets, and won the xx award.
Generally speaking, try to keep your self-introduction between 3-5 minutes. The first priority is to be concise and to the point, followed by highlighting your abilities and strengths.
For ordinary technical interviewers, self-introduction is just a habitual opening statement before the interview. Generally, the basic information listed on the resume has already satisfied their basic understanding of you. But for supervisor-level interviewers or HR, they will value your personality, behavioral habits, stress resistance and other comprehensive abilities. Therefore, you should be as positive as possible during the interview process, have broad hobbies, like continuous learning, like teamwork, and be able to work overtime unconditionally, etc. Of course, I don't mean to let you cheat, but in this environment, these "side abilities" are also magic weapons that can improve your competitiveness to a certain extent.
In the current market situation, when you receive an interview notice, there is a high probability that it is because of your project experience and the position you are recruiting for. More in line. Therefore, you should pay extra attention to the preparation of the project, such as:
Deep dig into thetechnologiesused in the project
Control of projectoverall designideas
Management of projectoperation process
Team collaborationability.
optimization points of the project
teleport’s source code, which took about thirty hours to write. It explains the function and role of each line of source code (but why are the reading and likes so low) .
Implementing development specifications, I have posted on the company's internal wiki, from naming, best practices to the use of various tool libraries. In the early stage when new people come in, I will give priority to follow up on their code quality
1.Team division of labor: Each person is responsible for the development of a product alone, and then I will generally designate a few people to develop public modules
2,Code Quality Assurance: Their code will be reviewed every week, and cross-review codes will be organized, and the output articles of the modified results will be placed in the wiki
3,Regular organizational meetings: Regular organizational meetings are held every week to synchronize their respective progress and risks, and allocate work tasks according to their own progress
4,Technology sharing: We will also organize irregular technology sharing. In the beginning, it was just me sharing, such as the micro front-end system, ice stark’s source code
5,public demand pool: such as the upgrade of webpack5/vite; the introduction of the upgrade of vue2.7 setup syntax sugar; use of pnpm; topology map performance optimization
6,Optimization project: After the first version of the product came out, I also initiated a special performance optimization project to improve first-screen loading performance. Packaging volume optimization; let everyone be responsible for the corresponding optimization items
I think there are generally two situations when working overtime:
First, the project progress is tight, so of course the project progress comes first, after all, everyone depends on this for a living
The second problem is my own ability. If I am not familiar with the business or introduce a new technology stack, then I think I not only have to work overtime to keep up, but also use my free time to study hard and make up for my shortcomings
I usually like to read, that is, I read some books on psychology, time management, and some speech skills in WeChat reading
Then I write articles, because I found It’s easy to forget simply taking notes, because you only record other people’s content, and write your own original articles. In this process, a very high proportion of knowledge can be converted into your own things, so in addition to your own gold-mining articles, I also often output articles on project outputs to the wiki
My other hobbies are playing basketball and singing with friends
Be sure to pay attention to technical interviews:Be concise and to the point, be detailed appropriately, and if you don’t understand, just say you don’t understand. Because the interview process is a face-to-face communication process with the interviewer, no interviewer would like a candidate who chatters for a long time without talking about the key points. At the same time, during the speaking process, the listener will passively ignore the parts that he is not interested in, so It is necessary to highlight the core features of a certain technology and appropriately expand around the core.
Big companies will basically screen candidates through algorithm questions. There are no shortcuts to algorithms. You can only answer questions step by step and then answer questions again. Those who are weak in this aspect should plan in advance and study.
The technical interview process will mainly ask questions about technologies related to the front-end field. Generally, the interviewer will be based on your establishment, and more often, the interviewer will be based on the interview questions he has prepared before, or the project team where he is working. Asking questions about relatively familiar technical points, because they are all unknowns, so all aspects are quite demanding.
If you want to enter a medium-to-large company with good development prospects, you can’t fool yourself by just memorizing other people’s experiences. Although each summary here is very brief, they are all I refined some of the core knowledge points after comprehensive study of each knowledge point, so I am not afraid of the interviewer's "divergent thinking."
The interview process generally involves the consideration of the following eight major types of knowledge:
JS/CSS/TypeScript/Framework (Vue, React)/Browser and Network/Performance Optimization/Front-End Engineering/ Architecture/Others

#So the technical preparation before the interview is by no means accomplished overnight. It also requires daily accumulation. For example, you can use ten to twenty minutes a day to study one of the small knowledge points. Comprehensive study, in the long run, no matter how many years of interviews, it will be enough to talk eloquently.
JS learning stud red envelope book and Mr. Yu Yu’sIn-depth JS series blogis basically ok
Common JS interview questions generally include these

The essence of a prototype is anobject.
When we create a constructor, this function will have aprototypeattribute by default, and the value of this attribute points to the prototype object of this function.
This prototype object is used to provide shared properties for the instance object created through the constructor, that is,is used to implement prototype-based inheritance and property sharing
So The instance objectwe create through the constructor functionwill inherit the above attributes from the prototype object of this function
When reading the attributes of an instance, if it cannot be found, it will look for the attributes in the prototype associated with the object. If it cannot be found, it will look for the prototype of the prototype until it finds the top level (the top level is The prototype ofObject.prototype, the value is null).
SoThe chain structure that is interconnected layer by layer through prototypes is called the prototype chain.
Definition: Closure refers to a functionthat references variables in the scope of other functions, usually implemented in nested functions.
Technically all js functions are closures. From a practical point of view, a function that meets the following two conditions is considered a closureUsage scenarios:
Application
this(runtime binding)
macro task queueand micro task queue. When the current execution stack is empty, the main thread will first check whether there is an event in the micro task queue. If there is an event, the micro task queue will be executed in sequence. The event in the task queue is called back until the micro task queue is empty; if it does not exist, it will be processed in the macro task queue.
Common macro tasks includesetTimeout(),setInterval(),setImmediate(), I/O , User interaction, UI rendering
Common microtasks includepromise.then(),promise.catch(),new MutationObserver、process.nextTick()
The essential difference between macro tasks and micro tasks
1. Ordinaryfunctionis directly called using()and passes parameters, such as:function test(x, y) { return x y},test(3, 4)
2. Called as an attribute method of the object, such as:const obj = { test: function (val) { return val } },obj.test(2)
3. UsecallorapplyCall, change the this point of the function, that is, change the execution context of the function
4,newYou can indirectly call the constructor to generate an object instance
Under normal circumstances, when the script tag is executed, it will download and execute a two-step operation. These two steps will block the parsing of HTML;
async and defer can The script'sdownload phasebecomes asynchronous execution (synchronously with HTML parsing);
Async will execute js immediately after the download is completed, which will block HTML parsing;
defer will wait until all HTML parsing is completed and executed before the DOMContentLoaded event.
DOM event flow three stages:
Capture stage: event The less specific nodes are the first to receive events, and the most specific nodes (trigger nodes) are the last to receive events. To intercept events before they reach their final destination.
For example, if you click on a div, the click event will be triggered in this order: document => Target phase When the event reaches the target node, the event enters the target stage. The event is triggered on the target node (executes the function corresponding to the event), and then flows back in reverse until it is propagated to the outermost document node. Bubbling phase After the event is triggered on the target element, it will continue to bubble up layer by layer along the DOM tree until Reach the outermost root node. All events must go through the capture phase and the target phase, but some events will skip the bubbling phase, such as the element gaining focus and losing focus blur which will not bubble Extension 1 What is the difference between e.target and e.currentTarget? For example: The event is bound to ul. When clicking on the li, the target is the clicked li, and the currentTarget is the ul of the bound event In the bubbling stage of the event (the above example), Function: Extension 2 addEventListener parameter Syntax: type: Type of listening event, such as: 'click'/'scroll'/'focus' listener: must be an object that implements the options: Specify the optional parameter object related to the listener useCapture: Boolean value, the default is false, the listener is executed at the end of the event bubbling phase, true means it is executed at the beginning of the capture phase . The function is to change the timing of the event to facilitate interception/non-interception. The author is mainly engaged in Vue-related development, and has also done react-related projects. Of course, react is only capable of doing projects. , so it is the kind of thing that is mentioned in the resume. The value of frameworks is not too many but their essence. Learning the Vue source code series makes me very confident in Vue. The same is true for the learning process. If you can master the principles of a framework, learning other frameworks is just a matter of time. 1. Data variability 2. Writing method 3 , diff algorithm Extension: Do you know react hooks? The writing of component classes is very heavy, and it is difficult to maintain if there are too many levels. Function components are pure functions, cannot contain state, and do not support life cycle methods, so they cannot replace classes. The design purpose of React Hooks is to enhance the functional component. You can write a fully functional component without using "classes" at all ##React Hooks means that components should be written as pure functions as much as possible. If external functions and side effects are needed, hooks should be used to "hook" the external code in. strategy. It will compare the lengths of the old and new child node arrays, first use the shorter length as the basis, and directly patch the part of the new child node. Then judge, if the length of the new child node array is longer, directly mount the remaining part of the new child node array; if the new child node array is shorter, uninstall the extra part of the old child node) . .The update of the child node with key is calledpatchKeyedChildren. This function is the familiar place to implement the core diff algorithm. The approximate process is to synchronize the head node, synchronize the tail node, and process new Add and delete nodes, and finally use the method of solving the longest increasing subsequence to deal with the unknown subsequence. This is to , and avoid the problem of child node status errors caused by in-place updates. 想详细了解这个知识点的可以去看看我之前写的文章:v-for 到底为啥要加上 key? vue2使用的是 所以 vue3 采用了 其实从api的原生性能上 而 vue 做的响应式性能优化主要是在将嵌套层级比较深的对象变成响应式的这一过程。 vue2的做法是在组件初始化的时候就递归执行 而vue3是在访问到子对象属性的时候,才会去将它转换为响应式。这种延时定义子对象响应式会对性能有一定的提升 前提:当同类型的 vnode 的子节点都是一组节点(数组类型)的时候, 步骤:会走核心 diff 流程 Vue3是快速选择算法 Vue2是双端比较算法 在新旧字节点的头尾节点,也就是四个节点之间进行对比,找到可复用的节点,不断向中间靠拢的过程 diff目的:diff 算法的目的就是为了尽可能地复用节点,减少 DOM 频繁创建和删除带来的性能开销 基于 MVVM 模型,viewModel(业务逻辑层)提供了数据变化后更新视图和视图变化后更新数据这样一个功能,就是传统意义上的双向绑定。 Vue2.x 实现双向绑定核心是通过三个模块:Observer监听器、Watcher订阅者和Compile编译器。 首先监听器会监听所有的响应式对象属性,编译器会将模板进行编译,找到里面动态绑定的响应式数据并初始化视图;watchr 会去收集这些依赖;当响应式数据发生变更时Observer就会通知 Watcher;watcher接收到监听器的信号就会执行更新函数去更新视图; vue3的变更是数据劫持部分使用了porxy 替代 Object.defineProperty,收集的依赖使用组件的副作用渲染函数替代watcher vue2 v-model 原理剖析 V-model 是用来监听用户事件然后更新数据的语法糖。 其本质还是单向数据流,内部是通过绑定元素的 value 值向下传递数据,然后通过绑定 input 事件,向上接收并处理更新数据。 单向数据流:父组件传递给子组件的值子组件不能修改,只能通过emit事件让父组件自个改。 给组件添加 如果想给绑定的 value 属性和 input 事件换个名称呢?可以这样: 在 Vue 2.2 及以上版本,你可以在定义组件时通过 model 选项的方式来定制 prop/event: 2、 一般使用 cors(跨域资源共享)来解决跨域问题,浏览器在请求头中发送origin字段指明请求发起的地址,服务端返回Access-control-allow-orign,如果一致的话就可以进行跨域访问 3、 Iframe 解决主域名相同,子域名不同的跨域请求 4、 浏览器关闭跨域限制的功能 5、 http-proxy-middleware 代理 预检 补充:http会在跨域的时候发起一次预检请求,“需预检的请求”要求必须首先使用OPTIONS方法发起一个预检请求到服务器,以获知服务器是否允许该实际请求。“预检请求”的使用,可以避免跨域请求对服务器的用户数据产生未预期的影响。 withCredentials为 true不会产生预请求;content-type为application/json会产生预请求;设置了用户自定义请求头会产生预检请求;delete方法会产生预检请求; xss基本概念 Xss (Cross site scripting)跨站脚本攻击,为了和 css 区别开来所以叫 xss Xss 指黑客向 html 或 dom 中注入恶意脚本,从而在用户浏览页面的时候利用注入脚本对用户实施攻击的手段 恶意脚本可以做到:窃取 cookie 信息、监听用户行为(比如表单的输入)、修改DOM(比如伪造登录界面骗用户输入账号密码)、在页面生成浮窗广告等 恶意脚本注入方式: 存储型 xss 黑客利用站点漏洞将恶意 js 代码提交到站点服务器,用户访问页面就会导致恶意脚本获取用户的cookie等信息。 反射性 xss 用户将一段恶意代码请求提交给 web 服务器,web 服务器接收到请求后将恶意代码反射到浏览器端 基于 DOM 的 xss 攻击 通过网络劫持在页面传输过程中更改 HTML 内容 前两种属于服务端漏洞,最后一种属于前端漏洞 防止xss攻击的策略 1、服务器对输入脚本进行过滤或者转码,比如将 2、充分利用内容安全策略 CSP(content-security-policy),可以通过 http 头信息的 content-security-policy 字段控制可以加载和执行的外部资源;或者通过html的meta 标签 3、cookie设置为 http-only, cookie 就无法通过 csrf基本概念 Csrf(cross site request forgery)跨站请求伪造,指黑客引导用户访问黑客的网站。 CSRF 是指黑客引诱用户打开黑客的网站,在黑客的网站中,利用用户的登录状态发起的跨站请求。简单来讲,CSRF 攻击就是黑客利用了用户的登录状态,并通过第三方的站点来做一些坏事。 Csrf 攻击场景 自动发起 get 请求 比如黑客网站有个图片: 黑客将转账的请求接口隐藏在 img 标签内,欺骗浏览器这是一张图片资源。当该页面被加载时,浏览器会自动发起 img 的资源请求,如果服务器没有对该请求做判断的话,那么服务器就会认为该请求是一个转账请求,于是用户账户上的 100 极客币就被转移到黑客的账户上去了。 自动发起 post 请求 黑客在页面中构建一个隐藏的表单,当用户点开链接后,表单自动提交 引诱用户点击链接 比如页面上放了一张美女图片,下面放了图片下载地址,而这个下载地址实际上是黑客用来转账的接口,一旦用户点击了这个链接,那么他的极客币就被转到黑客账户上了 防止csrf方法 1、设置 cookie 时带上SameSite: strict/Lax选项 2、验证请求的来源站点,通过 origin 和 refere 判断来源站点信息 3、csrf token,浏览器发起请求服务器生成csrf token,发起请求前会验证 csrf token是否合法。第三方网站肯定是拿不到这个token。我们的 csrf token 是前后端约定好后写死的。 websocket是一种支持双向通信的协议,就是服务器可以主动向客户端发消息,客户端也可以主动向服务器发消息。 It establishes a connection based on the HTTP protocol and has good compatibility with the http protocol, so it can pass the HTTP proxy server; there is no origin restriction. WebSocket is an event-driven protocol, which means it can be used for true real-time communication. Unlike HTTP (where updates must be constantly requested), with websockets, updates are sent as soon as they are available WebSockets will not automatically recover when the connection is terminated. This is a mechanism that needs to be implemented by yourself in application development , which is also one of the reasons why there are many client-side open source libraries. devServers like webpack and vite use websocket to implement hot updates Performance optimization is a point that medium and large companies pay great attention to. Because it is closely related to the KPIs of front-end people, it will naturally be an interview question. Regular customer. From a cache perspective In terms of network, it is more commonly used to use CDN for static resources In terms of packaging Code level First screen speed improvement #vue Common performance optimization methods You can obtain various performance indicator data through The complete front-end monitoring platform includes: data collection and reporting, data sorting and storage, and data display Web page performance indicators: The above indicators can be obtained throughPerformanceObserver 首屏渲染时间计算:通过 首先应该避免直接使用 DOM API 操作 DOM,像 vue react 虚拟 DOM 让对 DOM 的多次操作合并成了一次。 样式集中改变,好的方式是使用动态 class 读写操作分离,避免读后写,写后又读 原来的操作会导致四次重排,读写分离之后实际上只触发了一次重排,这都得益于浏览器的渲染队列机制: 当我们修改了元素的几何属性,导致浏览器触发重排或重绘时。它会把该操作放进渲染队列,等到队列中的操作到了一定的数量或者到了一定的时间间隔时,浏览器就会批量执行这些操作。 使用 通过 documentFragment 创建 dom 片段,在它上面批量操作 dom ,操作完后再添加到文档中,这样只有一次重排(示例:一次性插入2000个div) 复制节点在副本上操作然后替换它 使用 BFC 脱离文档流,重排开销小 Css 中的 优化请求数 减小图片大小 缓存 非响应式变量可以定义在 访问局部变量比全局变量块,因为不需要切换作用域 尽可能使用 使用 v8 引擎时,运行期间,V8 会将创建的对象与隐藏类关联起来,以追踪它们的属性特征。能够共享相同隐藏类的对象性能会更好,v8 会针对这种情况去优化。所以为了贴合”共享隐藏类“,我们要避免”先创建再补充“式的动态属性复制以及动态删除属性(使用delete关键字)。即尽量在构造函数/对象中一次性声明所有属性。属性删除时可以设置为 null,这样可以保持隐藏类不变和继续共享。 避免内存泄露的方式 避免强制同步,在修改 DOM 之前查询相关值 避免布局抖动(一次 JS 执行过程中多次执行强制布局和抖动操作),尽量不要在修改 DOM 结构时再去查询一些相关值 合理利用 css 合成动画,如果能用 css 处理就交给 css。因为合成动画会由合成线程执行,不会占用主线程 避免频繁的垃圾回收,优化存储结构,避免小颗粒对象的产生 感兴趣的可以看看我之前的一篇性能优化技巧整理的文章极意 · 代码性能优化之道 Внешнее проектирование — это наиболее важный навык на пути развития внешнего интерфейса.Все функции, которые могут повысить эффективность front-end developmentare Может использоваться как часть front-end разработки. Те, кто только начинает, могут начать с создания каркаса с нуляДлинная статья в 10 000 слов объясняет весь процесс создания фреймворка vue3 vite2 ts4 корпоративного уровня с нуля Для интервью, Самое важное, что нужно проверить, — это степень владения упаковочными инструментами. Webpack — это пакет, который предоставляет функции упаковки статических ресурсов для современных JS-приложений. Основной процесс состоит из трех этапов: этап инициализации, этап построения и этап генерации 1. На этапе инициализации параметры инициализации считываются из файла конфигурации, объекта конфигурации и параметров оболочки. и сравнивается со значением по умолчанию. Конфигурация объединяется в окончательные параметры, а также создает объект компилятора компилятора и инициализирует его рабочую среду 2. На этапе сборки компилятор выполнит свой метод run() для запустите процесс компиляции, который сначала подтвердит файл записи, начиная с файла записи, выполните поиск всех файлов, которые прямо или кратко связаны с файлом записи, для создания зависимых объектов, а затем создайте объекты модуля на основе зависимых объектов. на этот раз загрузчик будет использоваться для преобразования модуля в стандартный контент js, а затем вызывать js. Интерпретатор преобразует контент в объект AST, а затем находит модули, от которых зависит модуль, из AST. Этот шаг является рекурсивным до тех пор, пока все На этом этапе были обработаны файлы зависимостей записей. Наконец, компиляция модуля завершена и получены переведенное содержимое каждого модуля и граф зависимостей между ними.Этот граф зависимостей представляет собой взаимосвязь отображения всех модулей, используемых в проекте. loader webpack может понимать только файлы JS и JSON, загрузчик по сути является преобразователем, который может конвертировать другие типы файлов в файлы, распознаваемые веб-пакетом Загрузчик преобразует модуль, созданный зависимым объектом, в стандартный js-контент во время создания этап веб-пакета. Например, vue-loader преобразует файлы vue в модули js, а графические шрифты преобразуются в URL-адреса данных с помощью url-loader. Это вещи, которые Webpack может распознать. В модуле.rules можно настроить разные загрузчики для разбора разных файлов , эта функция Apply имеет компилятор параметров, который является объектом компилятора, созданным на этапе инициализации веб-пакета. Вы можете вызывать перехватчики в объекте компилятора для регистрации обратные вызовы для различных перехватчиков.Эти перехватчики действуют на протяжении всего жизненного цикла компиляции. Таким образом, разработчики могут вставлять в него определенный код с помощью обратных вызовов для выполнения определенных функций. MiniCssExtractPlugin Браузер, с одной стороны, ожидает получения новейших ресурсов каждый раз, когда запрашивает ресурс страницы; с другой стороны , он ожидает, что объекты Cache могут быть повторно использованы, если ресурсы не изменились. В настоящее время, используя имя файла и значение хеш-функции файла, вы можете определить, был ли ресурс обновлен, просто используя имя файла. В Webpack есть встроенный метод расчета хеша.Для сгенерированных файлов вы можете добавить поле хеш-функции в выходной файл. #hash : каждый раз при сборке проекта будет генерироваться хеш, который связан для всего проекта, и в любом месте проекта есть изменения. Он изменится ##хеш содержимого хеш чанка Потому что после упаковки веб-пакета каждый входной файл и его зависимости в конечном итоге будут генерировать отдельный js-файл. Использование chunkhash в это время может гарантировать точность обновления всего упакованного содержимого. Расширение: хэш загрузчика файловУ некоторых учащихся могут возникнуть следующие вопросы. Часто можно увидеть, что при обработке некоторых изображений и упаковке загрузчика файлов шрифтов [name]_[hash:8].[ext] Но если оно изменено, генерируется хеш изображения другими файлами проекта, такими как index.js, не изменилось. Здесь следует отметить, что хэш-поле file-loader, заполнитель, определенный самим загрузчиком, не соответствует встроенному хеш-полю веб-пакета. Хеш здесь заключается в использовании алгоритмов хеширования, таких как md4, для хэширования содержимого файла. Поэтому, пока содержимое файла остается неизменным, хеш будет оставаться согласованным. Vite в основном состоит из двух частей Среда разработки Vite использует просмотр Сервер анализирует импорт, компилирует и возвращает их на серверную сторону по требованию, полностью пропуская концепцию упаковки, и сервер может использовать их по мере необходимости (что эквивалентно преобразованию файлов, которые мы разрабатываем, в формат ESM и их отправке). непосредственно в браузер) Когда браузер анализирует импорт HelloWorld из './comComponents/HelloWorld.vue', он отправляет запрос на текущее доменное имя для получения соответствующего ресурса (ESM поддерживает анализ относительных путей) , и браузер напрямую загружает соответствующий файл и затем анализирует его в модуль Record (откройте сетевую панель и вы увидите, что данные ответа — это все ESM типа js). Затем создайте экземпляр и выделите память для модуля, а также установите отношения отображения между модулем и памятью в соответствии с операторами импорта и экспорта. Наконец запустите код. vite запустит сервер koa для перехвата запроса браузера на ESM, найдет соответствующий файл в каталоге по пути запроса, обработает его в формат ESM и вернет клиенту. Горячая загрузка Vite устанавливает соединение через веб-сокет между клиентом и сервером. После изменения кода сервер отправляет сообщение, уведомляющее клиента о запросе на изменение кода модуля. После завершения горячего обновления это означает, какое представление было изменено.file повторно запросит этот файл, таким образом гарантируя, что на скорость горячего обновления не влияет размер проекта. Среда разработки будет использовать esbuild для предварительного создания кеша для зависимостей. Первый запуск будет медленнее, а последующие запуски будут напрямую считывать кеш. 0. Элемент конфигурации скрипта можно определить в файле package.json, который может определять ключ и значение запущенного скрипта 1. Во время установки npm npm прочитает конфигурацию ивыполнит программную ссылку скриптана каталог #2. Другая ситуация — просто выполнить команду сценария, например npm run build, и фактически запустить node build.js., то есть: используйте node для выполнения файла build.js ES6 CommonJS Режим агента: укажите замену или заполнитель для символа объекта в чтобы контролировать доступ к ней Например, чтобы реализовать функцию отложенной загрузки картинок, сначала используйте Определение шаблона декоратора: без изменения сам объект включен, динамическое добавление методов к объектам во время работы программы обычно используется для сохранения исходных методов неизмененными, а затем монтирования других методов к исходным методам для удовлетворения существующих потребностей. Декоратор типа typescript является типичным шаблоном декоратора, а примесь в vue гарантирует, что класс имеет только экземпляр и предоставить глобальную точку доступа к нему. Метод реализации заключается в том, чтобы сначала определить, существует ли экземпляр. Если он существует, он будет возвращен напрямую. Если он не существует, он будет создан, а затем возвращен. Это гарантирует, что класс имеет только один объект экземпляра Например, субприложение Ice Stark, один раз гарантированно отрисовывается только одно субприложение #1 Хотя в обоих режимах есть подписчики и издатели (конкретных наблюдателей можно считать подписчиком, а конкретную цель можно считать издателем), но режим наблюдателя запланирован конкретной целью, а режим публикации/подписки единообразно корректируется центром планирования, поэтому между подписчиком и издателем режима наблюдателя существуют зависимости, а в модели публикации/подписки - нет. 2. Оба шаблона можно использовать для слабой связи, улучшения управления кодом и возможности повторного использования. 3. В режиме наблюдателя наблюдатель знает Субъекта, а Субъект ведет записи о наблюдателе. Однако в модели публикации-подписки издатель и подписчик не знают о существовании друг друга. Они общаются только через агента сообщений 4. Режим наблюдателя большую часть времени является синхронным. Например, при возникновении события субъект вызывает метод наблюдателя. Модель публикации-подписки в основном асинхронна (с использованием очереди сообщений) Какой тип данных является регулярным выражением? — это объект, Обычный жадный режим и нежадный режим? Квантор Жадный режим #В обычных правилах квантификатор, указывающий количество раз, по умолчанию является жадным и будет соответствовать максимальной длине как как можно больше, например Нежадный режим Добавьте Жадные и нежадные функции Как жадный, так и нежадный режим требуютобратного отслеживаниядля выполнения соответствующей функции Эксклюзивный режим Эксклюзивный режим очень похож на жадный режим. Эксклюзивный режим будет соответствовать как можно большему количеству совпадений. Если сопоставление не удастся, оно завершится без возврата, что экономит время. Запись: используйте после квантификатора. Преимущества и недостатки: монопольный режим имеет хорошую производительность и может сократить время сопоставления и ресурсы ЦП; но в некоторых случаях сопоставление невозможно быть достигнуто, например: 概念:前端自动化测试领域的, 用来验证独立的代码片段能否正常工作 1、可以直接用 Node 中自带的 assert 模块做断言:如果当前程序的某种状态符合 assert 的期望此程序才能正常执行,否则直接退出应用。 2、常见单测工具:Jest,使用示例 babel 用途 bebel 如何转换的? 对源码字符串 parse 生成 AST,然后对 AST 进行增删改,然后输出目标代码字符串 转换过程 parse 阶段:首先使用 transform 阶段:接着使用 generate 阶段:使用 好的,以上就是我对三年前端经验通过面试题做的一个总结了,祝大家早日找到心仪的工作~=>=> ;
e.targetPoints to the object that triggers event listening.e.currentTargetPoints to the object to which the listening event is added.
let ul = document.querySelectorAll('ul')[0] let aLi = document.querySelectorAll('li') ul.addEventListener('click',function(e){ let oLi1 = e.target let oLi2 = e.currentTarget console.log(oLi1) // 被点击的li console.log(oLi2) // ul console.og(oLi1===oLi2) // false })
e.currenttargetande.targetare not equal, but in the target stage of the event,e.currenttargetande.targetare equale.targetcan be used to implementevent delegation, The principle is to add event listening to the parent element through event bubbling (or event capturing), and e.target points to the element that triggers the trigger eventaddEventListener(type, listener); addEventListener(type, listener, options || useCapture);
EventListenerinterface, or afunction. When the monitored event type is triggered, it will be executed
preventDefault()AbortSignal, when itsabort()method is called , the listener will be removedVue Chapter

The difference between vue and react
setStateoronchange
reactmainly uses the diff queue to save which DOMs need to be updated, get the patch tree, and then Unified operation to update DOM in batches. , you need to useshouldComponentUpdate()to manually optimize react rendering.vue component communication method
props / $emit
Vue in the process of updating a group of child nodes of the same type of vnode (such as the list node rendered by v-for), in order to reduce the DOM Performance overhead of frequent creation and destruction:The update of the child node array without key is through the
in-place update
To sum up, if you use v-for to traverse constants or the child nodes are nodes without "state" such as plain text, you can use the writing method without adding a key. However, in the actual development process, it is recommended to add the key uniformly, which can realize a wider range of scenarios and avoid possible status update errors. We can generally use ESlint to configure the key as a required element of v-for.vue3 相对 vue2的响应式优化
Object.defineProperty去监听对象属性值的变化,但是它不能监听对象属性的新增和删除,所以需要使用$set、$delete这种语法糖去实现,这其实是一种设计上的不足。proxy去实现响应式监听对象属性的增删查改。proxy是比Object.defineProperty要差的。Object.defineProperty把子对象变成响应式的;Vue 核心diff流程
vue双向绑定原理
v-model 原理
// 比如 // 等价于
v-model属性时,默认会把value作为组件的属性,把input作为给组件绑定事件时的事件名:// 父组件
tag to have no cross-domain restrictions and only support the get interface. No one should use this anymore
XSS 和 CSRF
code:转换成code:3f1c4e4b6b16bbbd69b2ee476dc4f83aalert('你被xss攻击了')2cacc6d41bbb37262a98f745aa00fbf0document.cookie来读取
websocket
Differences between Post and Get
Performance Optimization Chapter

What are the means for performance optimization
Technical points of front-end monitoring SDK
window.performance
MutationObserver监听document对象的属性变化如何减少回流、重绘,充分利用 GPU 加速渲染?
// bad 强制刷新 触发四次重排+重绘 div.style.left = div.offsetLeft + 1 + 'px'; div.style.top = div.offsetTop + 1 + 'px'; div.style.right = div.offsetRight + 1 + 'px'; div.style.bottom = div.offsetBottom + 1 + 'px'; // good 缓存布局信息 相当于读写分离 触发一次重排+重绘 var curLeft = div.offsetLeft; var curTop = div.offsetTop; var curRight = div.offsetRight; var curBottom = div.offsetBottom; div.style.left = curLeft + 1 + 'px'; div.style.top = curTop + 1 + 'px'; div.style.right = curRight + 1 + 'px'; div.style.bottom = curBottom + 1 + 'px';
display: none后元素不会存在渲染树中,这时对它进行各种操作,然后更改 display 显示即可(示例:向2000个div中插入一个div)transform、opacity、filter、will-change能触发硬件加速大图片优化的方案
background-url和backgroun-position来显示图标background-url来懒加载
代码优化
created钩子中使用 this.xxx 赋值const声明变量,注意数组和对象
Внешнее проектирование

Процесс выполнения и жизненный цикл webpack
3.На этапе генерации объедините скомпилированные модули в фрагменты, а затем преобразуйте каждый фрагмент в отдельный файл и выведите его в список файлов.После определения выходного содержимого определите выходной путь и имя файла в соответствии с конфигурацией. , запишите содержимое файла в файловую систему
webpack's плагин и загрузчикСуть плагина – это класс с apply functionНапример, плагин stylelint может указать тип файла и диапазон файлов, которые Stylelint должен проверить; HtmlWebpackPlugin используется для создания упакованных файлов шаблонов; MiniCssExtactPlugin извлекает все CSS в независимые фрагменты, а stylelintplugin может предоставлять стили во время этап разработки, функция проверки.
хэш-стратегия webpack
Webpack имеет три встроенных хеша
принцип vite
Сравнение между webpack и vite
Принцип горячего обновления Webpack просто если это произойдет, то если зависимость (например,a.js) изменится, томодуль, в котором находится зависимость, будет обновлен и появится новыймодульбудет снова отправлен в браузер. Каждое горячее обновление будет повторно создаватьbundleКакие оптимизации были сделаны
0. Обновите версию веб-пакета с 3 до 4. Фактические измерения показывают, что скорость упаковки увеличивается на десятки секунд1. SplitChunksPlugin разделяет общий модуль и выводит отдельные фрагменты. Как и некоторые сторонние зависимые библиотеки, его можно разделить отдельно, чтобы отдельные фрагменты не были слишком большими.2.Функция DllPlugin такая же, как и выше.Эта зависимая библиотека эквивалентна отделению от бизнес-кода.Только когда версия самой зависимой библиотеки изменится, она будет переупакована, улучшая скорость упаковки3. Работа загрузчиков синхронна, каждый модуль будет выполнять все загрузчики
4. исключение/включение указывает диапазон соответствия; alias указывает псевдоним пути;5. постоянное хранилище кэш-загрузчика;6. Проект ESM включает тег useExport и использует встряхивание дерева7.исключить/включить для указания диапазона соответствия;псевдоним указывает псевдоним пути;постоянство загрузчика кэша Хранилище;8.terserPlugin может обеспечить сжатие кода, удаление комментариев и пробелов; MiniCssExtractPlugin сжимает CSS###процесс выполнения запуска npm
node_modules/.bin,одновременно. /binДобавьтев переменную среды$PATH, поэтому, если вы запускаете команду напрямую глобально, она будет искать в глобальном каталоге. Если команда не может быть найдена, будет выдана ошибка сообщил. Например, npm run start выполняет webpack-dev-server с параметрамиРазница между ESM и CJS
Шаблоны проектирования
Режим агента
loadingкартинку, чтобы занять место, а затем загружайте картинку асинхронно и ждите пока картинка не загрузится.Затем загрузите готовое изображение в тегimgШаблон декоратора
Шаблон с одним регистром
Режим наблюдателя и режим публикации-подписки
Другие
Регулярное выражение
let re = /ab c/эквивалентноlet re = new RegExp('ab c')*: 0 или более раз;?: 0 или 1 раз;: от 1 до нескольких раз;{m}: появляется m раз;{m,}: появляется как минимум m раз;{m, n}: появляется от m до n разa*будет соответствовать как можно большему количеству a в обратном направлении от первого соответствующего a, пока a не исчезнет.?после квантора, чтобы стать нежадным режимом. Нежадный режим означает поиск минимальной длины и удовлетворение условий
Обычное регулярное сопоставление
#Обычный
Текст
Результат
жадный режим
a{1,3}ab
aaab
match
не жадный режим
##Эксклюзивный режим
a{1,3}?ab
aaab
Match
a{1,3} ab to соответствует строке aaab, a{1,3} будет использовать все первые три символа a и не будет выполнять возврат.
a{1,3} ab
aaab
не соответствует
单元测试
function multiple(a, b) { let result = 0; for (let i = 0; i < b; ++i) result += a; return result; } const assert = require('assert'); assert.equal(multiple(1, 2), 3));const sum = require('./sum'); describe('sum function test', () => { it('sum(1, 2) === 3', () => { expect(sum(1, 2)).toBe(3); }); // 这里 test 和 it 没有明显区别,it 是指: it should xxx, test 是指 test xxx test('sum(1, 2) === 3', () => { expect(sum(1, 2)).toBe(3); }); })babel原理和用途
@babel/parser将源码转换成 AST@babel/traverse遍历 AST,并调用 visitor 函数修改 AST,修改过程中通过@babel/types来创建、判断 AST 节点;使用@babel/template来批量创建 AST@babel/generate将 AST 打印为目标代码字符串,期间遇到代码错误位置时会用到@babel/code-frame
Оператор
#.
Описание
Экземпляр
представляет любой одиночный символ
Набор символов, задающий диапазон для одного символа
[ ]
[abc]
представляет a, b, c, [a-z] представляет один символ a-z
[^ ]
Набор символов, дающий диапазон исключения для один символ
Предыдущий символ расширяется ноль или бесконечное количество раз
[^abc] представляет один символ, который не является a, b или c
##_
abc_
представляет ab, abc, abcc, abccc и т. д.
##`
#Любой из левых и правые выражения
` abc
def` означает abc, def
$
соответствует концу строки
abc$ Представляет abc и в конце строки
#( )
Знак группировки является только внутренним. Вы можете использовать
(abc)
для обозначения abc, `(abc
#def)` для обозначения abc, def
\D
Нечисловой
#\dЧисло, эквивалентное 0-9
##\S Видимые символы
##\s
Пробелы (пробелы, новые строки, табуляции и т. д.)
##\WНесловесные символы
##\w символов слова, эквивалентных [a-z0-9A -Z_]
## Соответствует началу строки
^abc
означает abc И в начале строки
# {m,n}
перед расширением Символ от m до n разab{1,2}c
означает abc, abbc
{m}
Расширение предыдущего символа m разab{2}c
означает abbc
Соответствует предыдущему символу как минимум m Times
#{m,}
#?
Предыдущий символ расширяется 0 раз или 1 раз
abc?
означает ab, abc