ReactJs
Giới thiệu
React là thư viện Javascript front-end phổ biến nhất trong phát triển web, được sử dụng bởi nhiều công ty lớn như Netflix, Airbnb, Instagram và The New York Times Với nhiều ưu điểm vượt trội trong phát triển ứng dụng web và mobile, React trở thành lựa chọn ưu việt hơn so với các framework khác như Angular.js.
React là một thư viện JavaScript mã nguồn mở, được thiết kế để xây dựng giao diện người dùng (UI) cho ứng dụng web và di động một cách nhanh chóng Với cấu trúc dựa trên các thành phần (component-based), React chỉ tập trung vào lớp giao diện (view layer) của ứng dụng, giúp tối ưu hóa quá trình phát triển front-end.
Trong kiến trúc MVC (Model View Controller), lớp view đóng vai trò quan trọng trong việc xác định cách mà ứng dụng được hiển thị và trải nghiệm bởi người dùng React, một thư viện JavaScript nổi bật, được phát triển bởi Jordan Walke, một kỹ sư phần mềm tại Meta.
Tại sao nên chọn React
Sự phổ biến của React ngày nay đã làm lu mờ tất cả các framework phát phiển front-end khác Dưới đây là lý do:
React giúp việc phát triển ứng dụng web động trở nên dễ dàng hơn, yêu cầu ít mã hóa hơn và cung cấp nhiều chức năng vượt trội.
6 với Javascript, ngôn ngữ mà việc coding sẽ trở nên phức tạp rất nhanh
React cải thiện hiệu suất ứng dụng web nhờ vào việc sử dụng Virtual DOM Công nghệ này cho phép React so sánh trạng thái trước đó của các component và chỉ cập nhật những phần trong React DOM bị thay đổi, thay vì cập nhật toàn bộ component như các ứng dụng web truyền thống Điều này giúp tăng tốc độ và hiệu quả cho các ứng dụng web.
❖ Tái sử dụng component: Component là nền tảng của bất kì ứng dụng
React là một thư viện JavaScript cho phép xây dựng ứng dụng bằng cách kết hợp nhiều component Mỗi component có logic và xử lý riêng, giúp tái sử dụng trong toàn bộ ứng dụng, từ đó tiết kiệm đáng kể thời gian phát triển.
React sử dụng luồng dữ liệu một chiều, cho phép lập trình viên lồng component con vào component cha khi xây dựng ứng dụng Điều này giúp dễ dàng hơn trong việc gỡ lỗi và xác định vị trí vấn đề trong ứng dụng.
React là một công cụ học tập nhanh chóng nhờ vào việc kết hợp giữa HTML cơ bản và các khái niệm Javascript, mang lại nhiều lợi ích bổ sung Tuy nhiên, khi sử dụng cùng với các công cụ và framework khác, người học cần dành thêm thời gian để nắm vững các thư viện của React.
React không chỉ được biết đến trong việc phát triển ứng dụng web mà còn có khả năng phát triển ứng dụng mobile thông qua React Native React Native, một framework phát triển từ React, rất phổ biến trong việc tạo ra các ứng dụng di động đẹp mắt Do đó, React thực sự có thể được sử dụng hiệu quả cho cả ứng dụng web và mobile.
Meta đã phát hành một tiện ích mở rộng cho Chrome, giúp quá trình debug các ứng dụng React trở nên nhanh chóng và dễ dàng hơn Công cụ này hỗ trợ debug cho cả ứng dụng web và mobile, mang lại trải nghiệm tốt hơn cho các lập trình viên.
Lược sử ra đời
React, được phát triển bởi Jordan Walke, một kỹ sư phần mềm tại Meta, đã ra mắt nguyên mẫu đầu tiên mang tên “FaxJS” Sự phát triển của React chịu ảnh hưởng từ XHP, một thư viện thành phần HTML dành cho PHP.
7 khai lần đầu tiên cho New’s Feed của Facebook năm 2011 và sau đó cho Instagram năm 2012 Nó được công bố mã nguồn tại JSConf US tháng năm 2013
React Native, introduced at the Facebook React Conf in February 2015 and released as open-source in March 2015, enables development for Android, iOS, and Universal Windows Platform (UWP).
Vào 18 tháng 4 năm 2017, Facebook công bố React Fiber, một thuật toán nội bộ cho việc rendering, trái ngược với thuật toán render cũ của React, Stack React Fiber trở thành nền tảng của bất kì cải tiến nào trong tương lai và phát triển các tính năng của thư việc React Cú pháp thật sự để lập trình với React không thay đổi, chỉ có cách cú pháp được thực thi bị thay đổi Hệ thống rendering cũ của
React, với kiến trúc Stack, đã được phát triển vào thời điểm mà việc theo dõi sự thay đổi động của ứng dụng chưa được chú trọng Điều này dẫn đến việc Stack gặp khó khăn trong việc xử lý các animation phức tạp Tuy nhiên, Fiber đã cải thiện điều này bằng cách chia nhỏ các animation thành nhiều phân đoạn có thể trải đều qua nhiều khung hình Tương tự, cấu trúc trang cũng được phân chia thành các phần có thể bảo trì và cập nhật liên tục Các hàm JavaScript và đối tượng Virtual DOM, được gọi là "fiber", cho phép thực hiện và cập nhật độc lập, từ đó mang lại trải nghiệm render mượt mà hơn trên màn hình.
Support for comment nodes {/*
*/} , Improved server-side rendering APIs, Removed React.autoBind, Support for the key prop, Improvements to forms, Fixed bugs
Improve Memory usage, Support for Selection and Composition events, Support for getInitialState and getDefaultProps in mixins, Added React.version and React.isValidClass, Improved compatibility for Windows
Added support for rows & cols, defer & async, loop for & , autoCorrect attributes Added onContextMenu events, Upgraded jstransform and esprima-fb tools, Upgraded browserify
The latest update introduces enhanced features including support for crossOrigin, download, hrefLang, mediaGroup, muted, sandbox, seamless, and srcDoc attributes Additionally, new PropTypes such as any, arrayOf, component, oneOfType, renderable, and shape have been added to React.PropTypes Furthermore, it now supports onMouseOver and onMouseOut events, as well as onLoad and onError events for elements.
Added support for srcSet and textAnchor attributes, add update function for immutable data, Ensure all void elements don't insert a closing tag
Improved SVG support, Normalized e.view event, Update $apply command, Added support for namespaces, Added new transformWithDetails API, includes pre-built packages under dist/,
MyComponent() now returns a descriptor, not an instance
The latest updates include the introduction of the spread operator ({ }) to replace the deprecated this.transferPropsTo method Additionally, support for HTML attributes such as acceptCharset, classID, and manifest has been added The API now features React.addons.batchedUpdates, and the use of @jsx React.DOM is no longer necessary Furthermore, issues related to CSS transitions have been resolved.
0.13.0 10 March 2015 Deprecated patterns that warned in 0.12 no longer work, ref resolution order has changed, Removed properties this._pendingState and this._rootNodeID,
Support ES6 classes, Added API React.findDOMNode(component), Support for iterators and immutable-js sequences, Added new features React.addons.createFragment, deprecated React.addons.classSet
Added support for srcLang, default, kind attributes, and color attribute, Ensured legacy props access on DOM nodes, Fixed scryRenderedDOMComponentsWithClass, Added react-dom.js
The latest update introduces significant improvements, including the use of document.createElement for initial rendering instead of generating HTML, eliminating unnecessary elements Enhanced SVG support is now available, while ReactPerf.getLastMeasurements() has become opaque Additionally, new deprecations come with warnings, and multiple small memory leaks have been addressed The React DOM now supports the cite and profile HTML attributes, as well as the cssFloat, gridRow, and gridColumn CSS properties.
Fix a batching bug, Ensure use of the latest object- assign, Fix regression, Remove use of merge utility, Renamed some modules
Include component stack information, Stop validating props at mount time, Add
React.PropTypes.symbol, Add onLoad handling to and onError handling to element, Add isRunning() API, Fix performance regression
15.3.0 30 July 2016 Add React.PureComponent, Fix issue with nested server rendering, Add xmlns, xmlnsXlink to support SVG attributes and referrerPolicy to HTML
10 attributes, updates React Perf Add-on, Fixed issue with ref
To enhance the performance of development builds, we focus on cleaning up internal hooks and upgrading fbjs, which collectively contribute to a faster startup time for React Additionally, we address critical issues such as fixing memory leaks in server rendering and resolving problems with the React Test Renderer Furthermore, we replace the trackedTouchCount invariant with a console.error for improved error handling.
React package and browser build no longer includes React DOM, Improved development performance, Fixed occasional test failures, update batchedUpdates API, React Perf, and ReactTestRenderer.create()
Restructure variable assignment, Fixed event handling, Fixed compatibility of browser build with AMD environments
Fixed build issues, Added missing package dependencies, Improved error messages
Added react-dom/test-utils, Removed peerDependencies, Fixed issue with Closure Compiler, Added a deprecation warning for React.createClass and React.PropTypes, Fixed Chrome bug
Fix compatibility with Enzyme by exposing batchedUpdates on shallow renderer, Update version of prop-types, Fix react-addons-create- fragment package to include loose-envify transform
15.6.0 13 June 2017 Add support for CSS variables in style attribute and
Grid style properties, Fix AMD support for addons
11 depending on react, Remove unnecessary dependency, Add a deprecation warning for React.createClass and React.DOM factory helpers
The latest updates in React include enhanced error handling through the introduction of "error boundaries," enabling developers to manage errors more effectively Additionally, React DOM now supports the passing of non-standard attributes, providing greater flexibility in component design Minor adjustments have been made to the setState behavior for improved performance, and the react-with-addons.js build has been removed to streamline the library Furthermore, React.createClass has been replaced with create-react-class, ensuring a more modern approach to component creation.
React.PropTypes as prop-types, React.DOM as react-dom-factories, changes to the behavior of scheduling and lifecycle methods
Discontinuing Bower Releases, Fix an accidental extra global variable in the UMD builds, Fix onMouseEnter and onMouseLeave firing, Fix
placeholder, Remove unused code, Add a missing package.json dependency, Add support for React DevTools
The latest updates include the introduction of a new officially supported context API and a new package, aimed at enhancing functionality Additionally, improvements have been made to prevent infinite loops during portal rendering with server-side rendering (SSR) The update also addresses issues related to this.state and resolves compatibility problems with Internet Explorer and Edge.
Prefix private API, Fix performance regression and error handling bugs in development mode, Add peer dependency, Fix a false positive warning in IE11 when using Fragment
Fix an IE crash, Fix labels in User Timing measurements, Add a UMD build, Improve performance of unstable_observedBits API with nesting
16.4.0 24 May 2018 Add support for Pointer Events specification, Add the ability to specify propTypes, Fix reading context,
Fix the getDerivedStateFromProps() support, Fix a testInstance.parent crash, Add
React.unstable_Profiler component for measuring performance, Change internal event names
The latest updates include support for React DevTools Profiler, improved error handling for various edge cases, and the integration of react-dom/profiling Additionally, the onAuxClick event has been added for enhanced browser compatibility, alongside the introduction of movementX and movementY fields for mouse events Furthermore, new fields for pointer events, including tangentialPressure and twist, have been implemented to enhance user interaction.
Add support for contextType, Support priority levels, continuations, and wrapped callbacks, Improve the fallback mechanism, Fix gray overlay on iOS Safari, Add React.lazy() for code splitting components
Fix performance of React.lazy for lazily-loaded components, Clear fields on unmount to avoid memory leaks, Fix bug with SSR, Fix a performance regression
Add Hooks, Add ReactTestRenderer.act() and ReactTe stUtils.act() for batching updates, Support synchronous thenables passed to React.lazy(), Improve useReducer Hook lazy initialization API
To enhance your React application, ensure to fix the incorrect bailout behavior in the useReducer() hook, which can lead to performance issues Additionally, address iframe warnings that appear in Safari DevTools for a smoother debugging experience It's also crucial to implement warnings when contextType is mistakenly set to Context.Consumer instead of Context, as well as to alert developers if contextType is assigned invalid values These improvements will help maintain code quality and optimize performance in your projects.
16.9.0 9 August 2019 Add React.Profiler API for gathering performance measurements programmatically
Remove unstable_ConcurrentMode in favor of unstable_createRoot
We addressed an edge case where a hook update was not being properly memoized and improved the heuristic for hydration to prevent incorrect hydration during updates Additionally, we optimized memory usage by clearing extra fiber fields during unmounting and resolved a bug affecting required text fields in Firefox We also prioritized using Object.is over inline polyfills when available and fixed issues related to mixing Suspense with error handling.
Fix regression in Next.js apps by allowing Suspense mismatch during hydration to silently proceed
Fix regression in react-native-web by restoring order of arguments in event plugin extractors
Fix mouseenter handlers from firing twice inside nested React containers Remove unstable_createRoot and unstable_createSyncRoot experimental APIs (These are available in the Experimental channel as createRoot and createSyncRoot.)
React DOM - Fix passive effects ( useEffect ) not being fired in a multi-root app
React Is - Fix lazy and memo types considered elements instead of components
Features added in React Concurrent mode
Fix regressions in React core library and React Dom
16.13.1 19 March 2020 Fix bug in legacy mode Suspense
Revert warning for cross-component updates that happen inside class render lifecycles
2020 Add support for the new JSX transform
"No New Features" enables gradual React updates from older versions
Add new JSX Transform, Changes to Event Delegation
2020 React DOM - Fixes a crash in IE11
React DOM - Remove an unused dependency to address the SharedArrayBuffer cross-origin isolation warning.
Các tính năng của React
JSX là một tiện ích mở rộng của Javascript, được sử dụng cùng với React để mô tả giao diện người dùng Việc sử dụng JSX cho phép viết cấu trúc HTML trong cùng một file với mã Javascript, giúp mã nguồn dễ hiểu và dễ gỡ lỗi hơn, đồng thời tránh việc sử dụng các cấu trúc DOM phức tạp của Javascript.
Khi tìm hiểu về React, chúng ta sẽ gặp khái niệm Virtual DOM Trước tiên, cần hiểu rõ DOM (Document Object Model) là gì DOM là một chuẩn mực do W3C phát triển, cho phép truy xuất và thao tác trên mã HTML hoặc XML thông qua các ngôn ngữ lập trình như Javascript.
DOM cho phép thao tác dữ liệu theo mô hình hướng đối tượng nhờ vào việc các phần tử trong DOM được cấu trúc thành các đối tượng, phương thức và thuộc tính dễ dàng truy xuất Những phần tử này được xem như các node và được thể hiện dưới dạng cây DOM.
Trong khi HTML là một đoạn code, DOM là một thể hiện trừu tượng của đoạn code đó trong bộ nhớ
HTML DOM cung cấp API để duyệt và chỉnh sửa các node Nó chứa các phương thức như getElementById hay removeChild
Chúng ta sử dụng Javascript để tương tác với DOM, nhưng sự tương tác này thường không hiệu quả do DOM được thiết kế cho giao diện người dùng tĩnh Các trang web trả về từ Server không yêu cầu cập nhật động, và khi DOM được cập nhật, nó cần phải cập nhật các node và render lại trang để phù hợp với CSS và cách bố trí.
Với sự phát triển của SPA (Single Page App), các thành phần trang web ngày càng có trách nhiệm trong việc lắng nghe và cập nhật giao diện người dùng (UI) theo những thay đổi mới Việc các trang hiển thị hàng nghìn node tự động và vẫn tiếp tục theo dõi các cập nhật trong tương lai không phải là điều hiếm gặp, nhưng điều này có thể dẫn đến chi phí cao.
Có nhiều phương pháp để các thành phần nhận biết khi nào có cập nhật dữ liệu và xác định xem có cần thiết phải tái tạo giao diện người dùng hay không.
Kiểm tra dữ liệu bẩn (dirty check) là quá trình rà soát tất cả các nút dữ liệu theo một khoảng thời gian nhất định để phát hiện sự thay đổi Tuy nhiên, phương pháp này không hiệu quả do yêu cầu phải duyệt qua từng nút một cách đệ quy, nhằm đảm bảo rằng dữ liệu không bị lỗi thời hay không còn chính xác.
Observable là một khái niệm quan trọng trong lập trình, nơi các thành phần chịu trách nhiệm lắng nghe các thay đổi xảy ra Khi dữ liệu được lưu trữ trong trạng thái, các thành phần sẽ theo dõi các sự kiện trên trạng thái đó Nếu có sự thay đổi, chúng sẽ tự động render lại giao diện người dùng (UI) để phản ánh những cập nhật mới nhất.
Trong danh sách các item, mỗi item đều có khả năng nhận yêu cầu cập nhật, cho thấy tính linh hoạt và khả năng tương tác của hệ thống.
Nếu một trong những item này thay đổi, thì DOM sẽ render lại toàn bộ, đây chính là lý do khởi nguồn của DOM không hiệu quả
Khi làm việc với một danh sách nhỏ, việc render lại tất cả các thành phần có thể không gây ảnh hưởng lớn, nhưng trong một ứng dụng đơn trang (SPA) với hàng trăm hoặc hàng nghìn thành phần, điều này trở nên không hiệu quả Để tối ưu hóa hiệu suất, lý tưởng nhất là chỉ render lại các item nhận được cập nhật, trong khi bỏ qua các item còn lại React sử dụng Virtual DOM để giảm thiểu việc làm không hiệu quả này, giúp cải thiện tốc độ và hiệu suất của ứng dụng.
Virtual DOM là một phiên bản trừu tượng nhẹ của DOM, có thể được xem như một bản sao của DOM Việc cập nhật Virtual DOM diễn ra nhanh chóng và hiệu quả hơn, giúp cải thiện hiệu suất của ứng dụng web.
Virtual DOM là một phiên bản nhẹ của DOM thực, giữ tất cả các thuộc tính giống như object DOM nhưng không thể hiển thị trên màn hình Sau mỗi lần render lại, một Virtual DOM mới sẽ được tạo ra Cần lưu ý rằng React không phải là công cụ đầu tiên giới thiệu Virtual DOM, vì một số thư viện khác cũng đã sử dụng phương pháp này Thực tế, React đang mở rộng sang nhiều nền tảng không phải web.
React-Native và React-VR là những phần mở rộng của React, trong đó các tính năng từ các phiên bản trước đã được tách ra và cung cấp dưới dạng các package riêng biệt Để sử dụng React trên web, chúng ta cần cài đặt và bao gồm React Dom.
React lưu trữ tất cả các bản sao của Virtual DOM để ghi lại trạng thái của DOM trước khi thực hiện bất kỳ cập nhật nào Sau đó, nó so sánh bản sao này với những thay đổi trong Virtual DOM để xác định các thay đổi cần được áp dụng.
Khi có thay đổi trong Virtual DOM, React thực hiện quá trình hòa hợp (reconciliation) bằng cách sử dụng thuật toán "diffing" để so sánh và xác định các cập nhật Nhờ đó, React chỉ cập nhật những phần tử đã thay đổi, trong khi bỏ qua các phần không thay đổi.
So sánh giữa React với Vue.Js và Angular
Hiện nay, lập trình front-end có thể thực hiện bằng bất kỳ ngôn ngữ lập trình nào, nhưng mã nguồn cần được chuyển đổi sang Javascript vì trình duyệt chỉ hỗ trợ thực thi mã Javascript Sự xuất hiện của WebAssembly, một xu hướng phát triển web quan trọng, có khả năng thay đổi tình hình này.
Javascript vẫn là một lựa chọn tối ưu để phát triển front-end Có rất nhiều
Các framework JavaScript hiện nay giúp việc phát triển client-side trở nên dễ dàng và nhanh chóng hơn Bài viết này sẽ đề cập đến ba framework phổ biến và hiệu suất cao thường được sử dụng trong các dự án cùng với React: Angular, Vue.Js và Ember.
Angular, được Google phát hành lần đầu vào năm 2010, đã trải qua nhiều cải tiến quan trọng Năm 2016, Angular 2 được giới thiệu như một phiên bản hoàn toàn mới Từ đó, các phiên bản cập nhật liên tục được phát hành, với Angular 13 là phiên bản ổn định mới nhất tính đến tháng 12 năm 2021.
❖ MVC framework: Angular là một framework MVW (Model-View- Whatever), thông thường được sử dụng như một MVC framework
Ứng dụng được phân chia thành ba thành phần liên kết chặt chẽ, giúp các nhà phát triển sử dụng Angular JS tạo ra những ứng dụng có cấu trúc rõ ràng, mang lại lợi ích cho các dự án phức tạp.
❖ Angular templates: template để tạo ra các component dễ đọc do hầu hết chúng sử dụng những thẻ tag HTML cơ bản
Liên kết dữ liệu hai chiều trong Angular cho phép các thay đổi ở model tác động trực tiếp đến view và ngược lại, mang lại sự dễ dàng trong việc thực thi cho các ứng dụng đơn giản Tuy nhiên, với các ứng dụng phức tạp hơn, liên kết dữ liệu một chiều (view-to-model hoặc model-to-view) lại giúp tăng tốc độ hoạt động và tiết kiệm tài nguyên, đáp ứng tốt hơn nhu cầu của ứng dụng.
❖ Cộng đồng lớn: Angular có một cộng đồng lớn đã phát tiển kể từ khi phát hành Angular JS và ngày càng lớn mạnh hơn kể từ khi Angular
Framework này đã đạt gần 500.000 lượt tải mỗi tuần trên npm và hơn 45.000 sao trên Github, cho thấy sự phổ biến đáng kể Điều này đồng nghĩa với việc có nhiều giải pháp tương thích với các phiên bản khác nhau của Angular, cùng với sự hỗ trợ từ các nhà phát triển và người dùng dày dạn kinh nghiệm mà không cần phải liên hệ với đội ngũ hỗ trợ chính thức.
Shadow DOM không được sử dụng mặc định, nhưng nó giải quyết vấn đề về tên độc nhất cho các phần tử trang, điều này rất quan trọng trong các dự án phức tạp Khi không sử dụng Shadow DOM, việc thay đổi style CSS trong một file có thể ảnh hưởng đến các file khác Shadow DOM cho phép trình duyệt chứa một cây con với các phần tử DOM để render mà không ảnh hưởng đến DOM chính Nó đóng gói các kiểu, tập lệnh và nội dung bên trong một phần tử tùy chỉnh, giúp ngăn chặn sự ảnh hưởng đến nội dung khác trong ứng dụng, đặc biệt là trong trường hợp của Angular 2+.
23 shadow DOM được kích hoạt trong các trình duyệt hỗ trợ nó Nếu không, quá trình đóng gói Shadow DOM được mô phỏng
Angular không sử dụng Virtual DOM, một bản sao đơn giản của DOM, cho phép thay đổi nhanh chóng mà không cần render lại toàn bộ Mặc dù Virtual DOM là xu hướng phổ biến trong các framework phát triển web hiện đại, Angular 2 lại áp dụng luồng dữ liệu một chiều để phát hiện và cập nhật các thay đổi của model, chỉ ảnh hưởng đến những phần liên quan khi model thay đổi.
Typescript là một phiên bản nâng cấp của Javascript, được phát triển bởi Microsoft, và Angular hỗ trợ sử dụng Javascript thuần túy Tuy nhiên, Angular được thiết kế để hoạt động tốt nhất với Typescript, mang lại sức mạnh và tính năng vượt trội cho các ứng dụng web.
Angular thật sự được giải phóng Có một điều bất lợi là chúng ta cần phải học lại các cú pháp đã được sửa đổi
Low rendering speed is a significant drawback, as the restriction on using Shadow DOM and the absence of Virtual DOM contribute to decreased performance Consequently, the rendering and re-rendering of views occur at a slower pace compared to other JavaScript frameworks.
Angular là một framework monolithic với mã nguồn nặng, dẫn đến việc cần nhiều tài nguyên và làm giảm tốc độ cũng như hiệu suất của web app Tuy nhiên, vấn đề này có thể được khắc phục thông qua kỹ thuật tree-shaking, cho phép loại bỏ các đoạn code không sử dụng Webpack là công cụ lý tưởng cho tree-shaking, hoạt động bằng cách quét các đoạn code, gom tất cả các module vào một file và xóa các export không cần thiết Kết quả là việc đóng gói sẽ giúp loại bỏ mã code không sử dụng, cải thiện hiệu suất ứng dụng.
Những điều thay đổi của Angular 13:
❖ Typescript 4.4 được hỗ trợ; kể từ ngày 5 tháng 10, những phiên bản cũ hơn 4.4.2 sẽ không còn được hỗ trợ ở core
❖ Phiên bản Node.js cũ hơn v12.20 không còn được hỗ trợ, do Angular package sử dụng chức năng export của Node.js với subpath patterns
❖ Thư viện lập trình rxjs (Reactive Extensions for Javascript) v7 được hỗ trợ
❖ Validator built-in như min, max, và minLength có được được disable hoặc enable một cách linh động
❖ Một API đơn giản ViewContainerRef.createComponent cho phép tạo các component một cách linh hoạt.
❖ Thông báo lỗi được cải thiện.
❖ Khả năng “build cache by default” được cải thiện chất lượng build.
❖ Angular Package Format 13 được giới thiệu, xóa bỏ View Engine- specific code từ package APF được sắp xếp hợp lý và hiện đại hóa.
❖ $locallize là một stable API.
❖ Điều kiện tùy chỉnh có thể được cài đặt trong ng_package.
❖ Router không thay thế URL của browser khi điều hướng mới hủy đi điều hướng đang hoạt động.
❖ Lớp wrappedValue không còn được hỗ trợ trong @angular/core.
❖ Behavior của SpyLocation sử dụng bở RouterTestingModule đã bị thay đổi để phù hợp với behavior của browser.
Vue.js là một framework hiện đại phổ biến cho việc xây dựng giao diện người dùng, được xem là sự thay thế tiềm năng cho Angular và React Ban đầu, Vue.js thu hút sự chú ý mạnh mẽ tại Trung Quốc và hiện nay đã lan rộng ra các nước phương Tây.
Vue là một framework MVC, tương tự như Angular, giúp chúng ta viết mã có cấu trúc tốt Điều này rất quan trọng trong việc phát triển các ứng dụng phức tạp.
Vue.js nổi bật với kích thước nhỏ gọn, mang lại lợi thế lớn cho người dùng nhờ không bao gồm nhiều tính năng thừa Framework này dễ dàng mở rộng thông qua các giải pháp từ bên thứ ba, tạo điều kiện thuận lợi cho việc phát triển So với Angular, một framework monolithic với nhiều tính năng tích hợp sẵn, Vue.js cho thấy sự linh hoạt và khả năng tùy chỉnh cao hơn.
Tree-shaking giúp loại bỏ mã không sử dụng trong ứng dụng, nhưng kích thước của framework vẫn lớn hơn nhiều so với Vue.
❖ Declarative template: Template trong Vue.js được viết bằng HTML, điều đó làm nó dễ dàng đọc mà không cần kiến thức về ngôn ngữ lập trình khác
❖ Virtual DOM: Do sử dụng virtual DOM, ứng dụng được built với Vue.js có hiệu suất cao khi so sánh với những framework front-end khác
❖ Liên kết dữ liệu hai chiều: Vue.js tự động đồng bộ hóa tất cả model với DOM
Quy mô cộng đồng phát triển
The React team members are dedicated full-time to developing core APIs, enhancing the engine that supports React DOM and React Native, maintaining React DevTools, and updating the documentation on the React website.
Các thành viên trong React team được liệt kê theo thứ tự bảng chữ cái bên dưới:
Quy mô cộng đồng sử dụng
React sở hữu một cộng đồng người dùng rộng lớn, vượt trội hơn so với các framework khác như Angular và Vue.js Hàng triệu lập trình viên tin tưởng sử dụng React, với gần 1.400 lập trình viên tham gia đóng góp vào sự phát triển của framework này.
Biểu đồ npm trend 5 năm gần đây
Google trend theo thời gian của React
Google trend theo khu vực của React
Repo của React đạt 180.000 sao
Kiến trúc
ReactJS là một thư viên của Facebook để lập trình client-side web app
React Native là một thư viện tương tự như React, được thiết kế để phát triển ứng dụng di động client-side có thể chạy trên cả Android và iOS Các khái niệm từ ReactJS cũng có thể áp dụng cho React Native, do đó cả hai thường được gọi chung là React.
React utilizes Facebook's homegrown architecture, Flux, which differs from other frameworks like AngularJS that employ bidirectional data flow In contrast, Flux maintains a unidirectional data flow, ensuring that data moves in a single direction.
Các ứng dụng React thường tích hợp thư viện quản lý trạng thái toàn cục Redux, tên gọi của nó được ghép từ “reducer” và “flux” Thư viện này hỗ trợ việc thực hiện chức năng “reduce” trong kiến trúc flux, giúp quản lý trạng thái một cách hiệu quả.
React không nhất thiết phải sử dụng Redux để quản lý global state; người dùng có thể chọn thư viện khác như MobX hoặc thậm chí không cần quản lý global state Redux là một thư viện độc lập, không thuộc về Facebook, và có thể áp dụng cho các framework khác ngoài React Tuy nhiên, sự kết hợp giữa React và Redux thường xuất hiện do tính tương thích cao giữa hai công nghệ này.
Redux có cấu trúc đơn giản với một trạng thái toàn cục, khi nhận hành động, nó sẽ trả về trạng thái mới dựa trên nội dung của hành động đó Để mở rộng các tính năng phức tạp hơn, chúng ta có thể sử dụng các middleware như Redux-persist, Redux-saga và Redux-logger.
ExpressJS
ExpressJs là gì
ExpressJS là một framework ứng dụng web mã nguồn mở và miễn phí, được phát triển trên nền tảng Node.js, cho phép thiết kế và phát triển ứng dụng web nhanh chóng Với việc chỉ cần kiến thức về JavaScript, lập trình viên có thể dễ dàng xây dựng các ứng dụng web và API, làm cho quá trình phát triển trở nên đơn giản hơn.
ExpressJS, một framework của Node.js, cung cấp mã nguồn sẵn có cho lập trình viên, giúp dễ dàng phát triển các ứng dụng web đơn trang, đa trang hoặc kết hợp Framework này nhẹ và hỗ trợ tổ chức ứng dụng web phía máy chủ theo kiến trúc MVC hiệu quả.
ExpressJS nâng cao khả năng của NodeJS, giúp đơn giản hóa quá trình lập trình API Nếu không có ExpressJS, việc xây dựng một API hiệu quả sẽ đòi hỏi nhiều lập trình phức tạp Nhờ vào ExpressJS, lập trình viên có thể làm việc với NodeJS một cách dễ dàng hơn.
ExpressJs được dùng để làm gì
ExpressJS hỗ trợ tổ chức kiến trúc back-end hiệu quả, giúp các nhà phát triển web triển khai mô hình MVC Việc này cho phép họ xây dựng một codebase back-end dễ dàng bảo trì.
ExpressJS là công nghệ hoạt động trên back-end, có thể được xem như "bộ não" của một trang web Nó xác định cách các trang được định tuyến và cho phép các nhà phát triển quản lý xác thực hiệu quả trên trang web.
Dưới đây là một số trường hợp sử dụng ExpressJs:
❖ Sử dụng cookie trên một trang web
❖ Thêm thanh tìm kiếm vào một trang web
❖ Cung cấp các tệp tĩnh như hình ảnh.
Lược sử ra đời
ExpressJs được phát triển bởi TJ Holowaychuk Bản phát hành đầu tiên, dựa theo lịch sử repo trên github của ExpressJS, là vào ngày 22 tháng 5 năm 2010, version 0.12
Vào tháng 6 năm 2014, StrongLoop đã mua lại quyền quản lý dự án, và sau đó, vào tháng 9 năm 2015, StrongLoop được IBM mua lại Đến tháng 1 năm 2016, IBM thông báo rằng ExpressJS sẽ được quản lý bởi chương trình Node.js Foundation.
The 4.17.2 patch release includes the following bug fixes:
• Fix handling of undefined in res.jsonp when a callback is provided
• Fix handling of undefined in res.json and res.jsonp when "json escape" is enabled
• Fix handling of invalid values to the maxAge option of res.cookie()
• Update to jshttp/proxy-addr module to use req.socket over deprecated req.connection
• Starting with this version, Express supports Node.js 14.x
For a complete list of changes in this release, see History.md
The 4.17.1 patch release includes one bug fix:
• The change to the res.status() API has been reverted due to causing regressions in existing Express 4 applications
For a complete list of changes in this release, see History.md
The 4.17.0 minor release includes bug fixes and some new features, including:
The express.raw() and express.text() middleware have been introduced to enhance request body parsing for raw payloads Utilizing the expressjs/body-parser module internally, applications that previously required this module separately can now seamlessly transition to using the built-in parsers.
• The res.cookie() API now supports the "none" value for the sameSite option
• When the "trust proxy" setting is enabled, the req.hostname now supports multiple X-Forwarded-For headers in a request
• Starting with this version, Express supports Node.js 10.x and 12.x
• The res.sendFile() API now provides and more immediate and easier to understand error when a non-string is passed as the path argument
• The res.status() API now provides and more immediate and easier to understand error when null or undefined is passed as the argument
For a complete list of changes in this release, see History.md
The 4.16.4 patch release includes various bug fixes:
• Fix issue where "Request aborted" may be logged in res.sendfile
For a complete list of changes in this release, see History.md
The 4.16.3 patch release includes various bug fixes:
• Fix issue where a plain % at the end of the url in the res.location method or the res.redirect method would not get encoded as %25
• Fix issue where a blank req.url value can result in a thrown error within the default 404 handling
• Fix the generated HTML document for express.static redirect responses to properly include
For a complete list of changes in this release, see History.md
The 4.16.2 patch release includes a regression bug fix:
• Fix a TypeError that can occur in the res.send method when a Buffer is passed to res.send and the ETag header is already set on the response
For a complete list of changes in this release, see History.md
The 4.16.1 patch release includes a regression bug fix:
• Update to pillarjs/send module to fix an edge case scenario regression that affected certain users of express.static
For a complete list of changes in this release, see History.md
The 4.16.0 minor release includes security updates, bug fixes, performance enhancements, and some new features, including:
• Update to jshttp/forwarded module to address a vulnerability This may affect your application if the following APIs are used: req.host, req.hostname, req.ip, req.ips, req.protocol
To enhance security, it is essential to update the dependency of the pillarjs/send module to resolve a vulnerability in the mime dependency This update is particularly important if your application processes untrusted string inputs through the res.type() API, as it may be susceptible to potential risks.
The pillarjs/send module has addressed the vulnerability associated with Node.js version 8.5.0 Utilizing any earlier version of Express.js alongside Node.js 8.5.0 exposes the express.static, res.sendfile, and res.sendFile APIs to potential security risks.
• Starting with this version, Express supports Node.js 8.x
The newly introduced "json escape" setting enhances security in Express applications by escaping characters in res.json(), res.jsonp(), and res.send() responses This feature prevents clients from misinterpreting the response as HTML, thereby upholding the Content-Type By implementing this setting, developers can safeguard their applications against a specific category of persistent XSS attacks.
• The res.download() method now accepts an optional options object
The express.json() and express.urlencoded() middleware offer built-in support for parsing request bodies, eliminating the need for the separate expressjs/body-parser module Applications currently using this module can seamlessly transition to the integrated parsers for enhanced efficiency.
The express.static() middleware and res.sendFile() method now allow for the configuration of the immutable directive in the Cache-Control header By setting this header along with a suitable maxAge, web browsers that support this feature will avoid making requests to the server as long as the file remains cached.
The latest update to the pillarjs/send module introduces an expanded list of MIME types, enhancing the accuracy of Content-Type settings for various files This release includes 70 new MIME types for different file extensions For a comprehensive overview of all changes, please refer to History.md.
The 4.15.5 patch release includes security updates, some minor performance enhancements, and a bug fix:
• Update to debug module to address a vulnerability, but this issue does not impact Express
The jshttp/fresh module has been updated to fix a security vulnerability that could impact your application This update is particularly relevant if you utilize the following APIs: express.static, req.fresh, res.json, res.jsonp, res.send, res.sendfile, res.sendFile, and res.sendStatus Ensure your application is updated to maintain security and functionality.
• Update to jshttp/fresh module fixes handling of modified headers with invalid dates and makes parsing conditional headers (like If-None-Match) faster
For a complete list of changes in this release, see History.md
The 4.15.4 patch release includes some minor bug fixes:
• Fix array being set for "trust proxy" value being manipulated in certain conditions
For a complete list of changes in this release, see History.md
The 4.15.3 patch release includes a security update and some minor bug fixes:
To enhance security, it is essential to update the dependency of the pillarjs/send module due to a identified vulnerability This update is particularly important if your application utilizes untrusted string inputs for the maxAge option in APIs such as express.static, res.sendfile, and res.sendFile, as it may pose risks to your application.
• Fix error when res.set cannot add charset to Content-Type
• Fix missing in HTML document
For a complete list of changes in this release, see History.md
The 4.15.2 patch release includes a minor bug fix:
• Fix regression parsing keys starting with [ in the extended (default) query parser
For a complete list of changes in this release, see History.md
The 4.15.1 patch release includes a minor bug fix:
• Fix compatibility issue when using the datejs 1.x library where the express.static() middleware and res.sendFile() method would incorrectly respond with 412 Precondition Failed
For a complete list of changes in this release, see History.md
The 4.15.0 minor release includes bug fixes, performance improvements, and other minor feature additions, including:
• Starting with this version, Express supports Node.js 7.x
• The express.static() middleware and res.sendFile() method now support the If-Match and If-Unmodified-Since request headers
• Update to jshttp/etag module to generate the default ETags for responses which work when Node.js has FIPS-compliant crypto enabled
• Various auto-generated HTML responses like the default not found and error handlers will respond with complete HTML 5 documents and additional security headers
For a complete list of changes in this release, see History.md
The 4.14.1 patch release includes bug fixes and performance improvements, including:
The latest update to the pillarjs/finalhandler module addresses an issue in Express where an Error object with a non-object headers property caused exceptions For a detailed overview of all changes in this release, please refer to History.md.
The 4.14.0 minor release includes bug fixes, security update, performance improvements, and other minor feature additions, including:
• Starting with this version, Express supports Node.js 6.x
• Update to jshttp/negotiator module fixes a regular expression denial of service vulnerability
• The res.sendFile() method now accepts two new options: acceptRanges and cacheControl
The "acceptRanges" option, which is enabled by default, allows for the acceptance of ranged requests; when disabled, it prevents the response from sending the Accept-Ranges header and disregards the Range request header Additionally, the "cacheControl" feature, also enabled by default, controls the ability to enable or disable caching.
Control response header Disabling it will ignore the maxAge option o res.sendFile has also been updated to handle Range header and redirections better
• The res.location() method and res.redirect() method will now URL-encode the URL string, if it is not already encoded
• The performance of the res.json() method and res.jsonp() method have been improved in the common cases
The jshttp/cookie module has been updated to enhance functionality, including support for the sameSite option in the res.cookie() method, allowing users to specify the SameSite cookie attribute However, it is important to note that this attribute is not yet fully standardized and may undergo changes in the future, with the possibility that some clients may disregard it.
The SameSite option can have several values: true, which enforces strict same-site policies by setting the SameSite attribute to Strict; false, which does not apply the SameSite attribute; 'lax', which applies a more lenient enforcement by setting the SameSite attribute to Lax; and 'strict', which also enforces strict same-site policies by setting the SameSite attribute to Strict.
• Absolute path checking on Windows, which was incorrect for some cases, has been fixed
• IP address resolution with proxies has been greatly improved
The req.range() method now includes a new options object with a combine option, which is set to false by default When enabled, this option allows for the combination of overlapping and adjacent ranges, returning them as if they were specified together in the header For a comprehensive overview of all changes in this release, please refer to History.md.
Lợi ích khi sử dụng ExpressJS
❖ Rất dễ học, chỉ cần chúng ta biết JavaScript, chúng ta sẽ không cần phải học một ngôn ngữ mới để học ExpressJS
❖ Giúp cho việc phát triển back-end dễ dàng hơn nhiều khi sử dụng ExpressJS
❖ Mã JavaScript được diễn giải thông qua Google V8 JavaScript Engine của Node.js Do đó, mã sẽ được thực hiện một cách nhanh chóng và dễ dàng
❖ ExpressJS rất đơn giản để tùy chỉnh và sử dụng theo nhu cầu
❖ Cung cấp một module phần mềm trung gian linh hoạt và rất hữu ích để thực hiện các tác vụ bổ sung theo phản hồi và yêu cầu
❖ Hỗ trợ phát triển ứng dụng theo mô hình MVC, đây là mô hình phổ biến cho việc lập trình web hiện nay.
Danh sách tính năng cơ bản
ExpressJS giúp phát triển máy chủ nhanh chóng bằng cách cung cấp nhiều tính năng thường dùng của Node.JS dưới dạng các hàm dễ sử dụng Điều này không chỉ tiết kiệm thời gian mà còn loại bỏ nhu cầu viết mã phức tạp trong nhiều giờ.
Middleware là thành phần của chương trình có khả năng truy cập vào cơ sở dữ liệu, yêu cầu từ client và các phần mềm trung gian khác Nó đóng vai trò quan trọng trong việc tổ chức hệ thống các chức năng khác nhau của ExpressJS.
❖ Routing: ExpressJS cung cấp cơ chế định tuyến nâng cao giúp duy trì trạng thái của trang web với sự trợ giúp của URL
ExpressJS offers templating engines that enable developers to create dynamic web content by constructing HTML templates on the server side.
Gỡ lỗi là một yếu tố quan trọng trong quá trình phát triển ứng dụng web thành công ExpressJS hỗ trợ việc này bằng cách cung cấp các cơ chế gỡ lỗi hiệu quả, giúp xác định chính xác vị trí lỗi trong ứng dụng web.
Một số công nghệ tương đương
Hapi.js is a REST API-based framework designed for building scalable and expandable web applications, developed by the mobile development team at Walmart Labs.
Hapi.js đã chứng minh khả năng mạnh mẽ của mình khi xử lý tất cả các yêu cầu từ ứng dụng di động của Walmart trong dịp Black Friday, chỉ với khoảng 10 CPU và 28GB RAM.
❖ Nó cung cấp các chức năng có thể tái sử dụng và lưu vào bộ nhớ cache mà chúng ta có thể truy cập trong toàn bộ ứng dụng
❖ Nó cung cấp các lớp trừu tượng giúp chia ứng dụng thành nhiều phần hợp lý
❖ Nó tuân theo phương pháp không conflic routing Các đường dẫn sẽ không xảy ra hiện tượng conflic Ưu điểm:
❖ Nó cung cấp một hệ thống plugin mạnh mẽ và có thể mở rộng giúp phát triển ứng dụng nhanh hơn và hiệu quả hơn
❖ Nó chủ yếu cung cấp các module như cơ chế bộ nhớ đệm, xác thực và xác thực đầu vào ngay lập tức
❖ Nó kiểm soát tốt hơn việc xử lý các request
Việc cấu trúc codebase không có quy tắc hay hướng dẫn cụ thể nào, do đó, việc tuân thủ tiêu chuẩn hoàn toàn phụ thuộc vào nhà phát triển Nếu không được tuân thủ nghiêm ngặt theo một tiêu chuẩn nhất định, điều này có thể dẫn đến các vấn đề nghiêm trọng trong quá trình phát triển phần mềm.
Mặc dù Scanfold đi kèm với các module được dựng sẵn, nhưng việc tạo và kiểm tra các endpoint vẫn phải thực hiện thủ công.
❖ Khi mà đã kết hợp chặt chẽ với một ứng dụng sử dụng Hapi.js, việc chuyển sang dùng một framework khác là một thách thức lớn
Xây dựng một ứng dụng doanh nghiệp từ đầu là một thách thức lớn, đòi hỏi sự duy trì cấu trúc mã và nguyên tắc thiết kế nhất quán trong toàn công ty Sails.js, với kiến trúc MVC của nó, giúp giải quyết những vấn đề này một cách hiệu quả.
46 based framework dành cho ứng dụng web dành cho các ứng dụng cấp doanh nghiệp
Nó tương tự như kiến trúc MVC trong các framework như Ruby on Rails, tuân theo nguyên tắc "convention over configuration", giúp phát triển ứng dụng thời gian thực một cách nhanh chóng.
❖ Nó sử dụng những tính năng bên trong ExpressJS
❖ Nó cung cấp WebSockets để xây dựng các ứng dụng theo thời gian thực
❖ Nó cung cấp ORM/ODM làm cho nó trở thành cơ sở dữ liệu bất khả thi
❖ Sails.js có khả năng tạo code mạnh mẽ Nó có một khái niệm được gọi là blueprintactions giúp việc tạo code một các hiệu quả
❖ Nó ưu tiên các quy ước hơn là config Ưu điểm:
❖ Kiến trúc MVC-based Vì vậy, nó tách các logic nghiệp vụ ra khỏi UI
❖ Nó cung cấp miễn phí JSON API generation Và chúng ta không cần thêm routing
❖ Nó cho phép chúng ta lưu trữ dữ liệu ở bất kỳ đâu Khi nó sử dụng waterline ORM/ODM, cơ sở dữ liệu của nó là bất khả thi
❖ Sails.js chậm với mức tiêu thụ bộ nhớ cao
❖ Việc quản lý các asset tĩnh trên ứng dụng có thể trở nên vụng về
❖ Đôi lúc, việc phát triển trên một ứng dụng có thể chậm và tiêu tốn thời gian
Vì vậy, cần có thời gian để khởi động trên máy chủ product
Koa.js là web framework mới nhất được thiết kế bởi team đằng sau Express
Koa.js ra đời để khắc phục những hạn chế của Express, đặc biệt là trong việc xử lý callback Với kích thước nhỏ gọn và các chức năng không đồng bộ được tích hợp sẵn, Koa.js mang đến giải pháp tối ưu cho việc phát triển ứng dụng web Nhóm phát triển đã quyết định cung cấp các tác vụ không đồng bộ như mặc định, giúp cải thiện hiệu suất và tính linh hoạt trong lập trình.
Koa là một framework hiện đại, được thiết kế để đảm bảo tính bền vững cho tương lai, và được xây dựng dựa trên ES6, phiên bản Javascript tiên tiến, giúp việc phát triển ứng dụng web trở nên dễ dàng hơn.
❖ Nó sử dụng ES6 generator để tạo các chức năng downstream hoặc upstream
Nó giúp chúng ta tránh được callback hell
❖ Nó cung cấp một module catchall dựng sẵn để kiểm soát lỗi hiệu quả hơn
❖ Nó sử dụng context object, là một gói chứa các đối tượng yêu cầu và phản hồi Ưu điểm
❖ Cực kỳ nhẹ chỉ với 550 dòng code
❖ Nó sử dụng một generator để tránh cái callback ngay từ lúc bắt đầu
❖ Sử dụng generator khiến cho ứng dụng khó chuyển sang framework khác trong tương lai Nó tạo ra kết nối chặt chẽ với framework
❖ Koa có cộng đồng nhỏ khi so sánh với ExpressJS
❖ Nó không tương thích với phần mềm trung gian kiểu express.
Cộng đồng phát triển và sử dụng
Express.js, được sáng lập bởi TJ Holowaychuk, đã được chuyển giao quyền quản lý cho StrongLoop vào năm 2014 Đến năm 2015, StrongLoop đã bán lại cho IBM Hiện nay, Express.js đang được quản lý bởi Node.js Foundation.
Quy mô cộng đồng sử dụng Express.js