Chào mọi người, đây là bài viết chia sẻ kinh nghiệm của bản thân mình khi tìm hiểu về công cụ create-react-app cho việc lập trình ReactJS trở nên dễ dàng hơn. Trong bài viết này, mình sẽ nói về những điều có thể cần thiết cần phải tinh chỉnh trước khi bắt đầu 1 dự án React của các bạn, cụ thể là sử dụng create-react-app với các thư viện redux, react-redux, redux-thunk, react-router, react-router-dom, sass, code spliting, jQuery, bootstrap, react-loadable, react-scrollchor, react-intl, react-select, react-datepicker, react-table, moment, ...
Đây là source GitHub của mình: https://github.com/huynhsamha/create-react-app-config
Còn đây là demo về 1 số phần mình làm: https://huynhsamha.github.io/create-react-app-config/
Bắt đầu với create-react-app
Nếu bạn mới bắt đầu sử dụng react hoặc chưa biết đến create-react-app thì mình nghĩ bạn nên sử dụng thằng này để làm quen với react, vì nó đã làm sẵn mọi thứ giúp ta, ta chỉ cần làm theo những gì ta muốn với công cụ này.
Trước tiên, bạn nên cài package
create-react-app mức global từ npm . npm install create-react-app -g hoặc nếu bạn dùng Ubuntu hay một số hệ điều hành khác, nó yêu cầu quyền root, bạn thêm sudo vào trước lệnh để thực thi.- Tạo mới project:
create-react-app react-app npm startoryarn start: start môi trường dev.npm buildoryarn buildbuild production.
Trong bài này, mình sử dụng
yarn, các bạn có thể sử dụng npm cũng được theo đúng cú pháp của npm.Thiết lập biến môi trường (environment variables)
Tạo các file lưu trữ biến môi trường, những file này theo như create-react-app nói nó sẽ nhận ra các biên được khai báo trong các file này.
- Trong terminal tại root của project:
touch .env .env.development .env.production - In
.env.development:REACT_APP_ENV=development - In
.env.production:REACT_APP_ENV=production
Note: chỉ mầy biến với prefix là
REACT_APP_ thì thằng create-react-app mới hiểu và đọc được, còn sử dụng nó thì mình nói sau.Post-Processing CSS
Khi viết CSS, ta thường quan tâm đến các thuộc tính hỗ trợ trên nhiều trình duyệt . Tuy nhiên
create-react-app sẽ lo cho ta việc này, do đó ta có thể yên tâm khi viết CSS 1 cách đơn giản. Đây là lời trích từ document của react:This project setup minifies your CSS and adds vendor prefixes to it automatically through Autoprefixer so you don’t need to worry about it.
CSS Preprocessor (Sass, Less etc.)
Nếu bạn nào đã dùng qua SASS , LESS, SCSS thì cũng biết sự lợi hại và tiện ích của những thằng này. Do đó nếu có thể tích hợp vào React thì khá thú vị.
create-react-app cũng hỗ trợ ta việc này, bằng cách thực hiện các bước sau:- In terminal:
yarn add node-sass-chokidar npm-run-all - In file
package.json:
{
"scripts": {
- "start": "react-scripts start",
- "build": "react-scripts build",
+ "start": "npm-run-all -p watch-css start-js",
+ "build": "npm-run-all build-css build-js",
+ "start-js": "react-scripts start",
+ "build-js": "react-scripts build",
+ "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
+ "build-css": "node-sass-chokidar src/ -o src/",
}
}
- In file
.gitignore:
# auto generated files (sass, less, ...)
src/**/*.css
Lúc này khi ta start de lên, khi có thay đổi gì ở file sass, thì nó sẽ tự build lại các file css cho ta và browser tự động được refresh.
Còn trong file .gitignore, ta thêm các file tự động sinh ra do sass để tránh gây conflict không cần thiết khi nhiều người commit.
Tạo server Node.JS
Nhiều lúc, ta cũng muốn sử dụng node cho thằng react 

Use express to initialization
mkdir server
cd server
express
Configuration
- Rename
app.jstoserver.js - Join
server.jsand./bin/www - Move
server.jsto root app - Insert dependencies in
package.json(which is generated byexpress) topackage.jsonin root (which is generated bycreate-react-app) - Remove dependencies not use (
serve-favicon,jade,ejs, etc.) - Remove all file in
server, execptroutes/index.js - Correct and customize file
server.js
Install dependencies package
yarn
Install package cors
Ta install package
cors để cross từ port 3000 localhost tới port 4200 localhost.localhost:3000(client-side, là port thằng react)localhost:4200(server-side, là port của node express)
yarn add corsStart server-client
yarn start or npm start: start client side (react): localhost:3000node server: start server-side (node express): localhost:4200Environment cho react app
Lúc ta phát triển (dev), ta sử dụng node ở port 4200, còn react ở port 3000, do đó để react có thể gọi request đến port 4200, ngoài sử dụng
cors như ở trên, ta cũng cần sử dụng biên môi trường (đã thiết lập ở bước trên) để lấy dữ liệu từ server node. Ngoài ra ta cũng có thể dùng proxy (tham khảo thêm google cách này).
Như đã nói ở trên, chỉ các biến
REACT_APP_ được khai báo trong các file tương ứng thì react mới biết được. Cụ thể ta dùng biến REACT_APP_ENV để phân biệt môi trường của server, nếu là production thì không cần phinh phức.- Create environment files: In your terminal:
mkdir src/environments
cd src/environments
touch env.development.js env.production.js index.js
- Edit the files as source code.
baseUrlis url to server.
Cấu trúc thư mục src trong react app
Styles
Tạo thư mục
styles trong src/ để chứa các biến variables, mixins, classes, common styles, or theme, etc. cho app react: + _variables.scss: khai báo các variables . + _mixins.scss: khai báo các mixins (dùng sass hoặc less) + _classes.scss: khai báo 1 số class hữu ích. + index.scss: import các file _ vào file này, để file index.scss ở ngoài thư thư mục tương ứng, còn trong file index.js, ta import style này vào ./styles/index.css + Nếu app của bạn sử dụng theme (như AdminLTE, Bootstrap, Material, Angular, Datatables, Charts, ...), ta ghi đề những style cần với file prefix là _ và import vô index.scssLibrary and packages
Trong thư mục
src, ta tạo thư mục lib để chứa các thư viện và package ta dùng trong app, chẳng hạn như jQuery, Bootstrap, Font-Awesome, Ionicons, Material, ...- Tạo file
index.jstronglibđể import các file trong thư mục này - Trong file
index.jsngoài thư mục app của ta, ta import thư mụclibvừa tạo chỉ bằng dòngimport './lib';
Utility service
Ta cũng tạo thư mục
services để chứa các tiện ích của app. Việc triển khai thư mục này ta sẽ bàn sau.Reducers - Actions
Nếu ta sử dụng
redux, ta cũng cần tạo 2 thư mục actions và reducers. Cụ thể triển khai ta sẽ bàn sau.Components
Ta tạo
components để chứa các components của app, trong đó ta chia ra thành:Layout Components
Tạo thư mục
layout để chứa luồng thực thi của app. Trong layout ta tạo hai file App.js và App.scss, ngoài ra còn chứa các thư mục Header, Footer, Sidebar, Menu, Body tương ứng cho việc điều hướng app.Common Components
Ta tạo
common để chứa các components dùng chung được sử dụng nhiều lần như Loading, Modal, Alert, Notification, Box, ...Pages Components
Tạo
pages để chứa các trang của 1 single page app, như Home, Dashboard, Profile, Form, Terms of Service, Support, Page not found, Error page,..jQuery
Installation
- In terminal:
yarn add jquery - In terminal:
touch src/lib/jquery.js: tạo file jquery config - COnfig file này như sau:
import $ from 'jquery';
// config jquery variables for other lib use jQuery (such as bootstrap)
window.$ = $;
window.jQuery = $;
How to use?
- In
lib/index.js, import by:import './jquery'; - In
index.jsat ngoài app,import './lib';(nếu như bạn chưa import). - Trong mỗi component, để sử dungj jquery mà react không báo lỗi, ta cần import:
import $ from 'jquery'; - jquery chỉ sử dụng kể từ
componentDidMount()trong vòng đời của 1 component react: - View Demo here
- View Implementation here
componentDidMount() {
// jQuery should declare at here
$(document).ready(() => {
$('#alert').click(() => alert('This is alert be jQuery'));
});
}
Recommend
Chỉ nên dùng jquery khi thực sự cần thiết. vì react đã hỗ trợ khá đủ.
Bootstrap 3, 4
Sử dụng cùng với jquery
Installation
- In terminal:
yarn add bootstrap(thêm @version cho version bạn sử dụng) - In terminal:
mkdir src/lib(nếu đã tạo thì bỏ qua) - In terminal:
touch src/lib/bootstrap.js - Cấu hình file này như sau (mình đang dùng bootstrap 4):
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.bundle.min.js';
How to use?
- In
lib/index.js, import by:import './bootstrap'; - In
index.jsat root,import './lib';(if you don't have). - Trong component, ta có thể sử dụng bootstrap 3, 4 như document của bootstrap.
- View demo with component
DemoBootstrap. - View Demo here
- View Implementation here
Sử dụng thông qua React Component - reactstrap
reactstrap là một package react cho bootstrap, tương đối ổn so với bootstrap nhưng không phải là hoàn thiện. Bạn có thể google package này để xem qua doc của nó.
Cũng có nhiều framework khác cho react, xây dụng sẵn các component cần thiết cho react, bạn có thể google các framewro hoặc package tương ứng.
Installation and Usage
- In terminal:
yarn add reactstrap@next - Only import Component to use as reactstrap document
- View demo with component
DemoReactstrap. - View Demo here
- View Implementation here
Font Awesome
Thông qua index.html
Ta có thể include trực tiếp thông qua
index/html bằng cdn, hoặc download rồi include vào.Sử dụng npm package
- In terminal:
yarn add font-awesome - Create file
lib/font-awesome.jsand add lineimport 'font-awesome/css/font-awesome.min.css'; - In
lib/index.js, import by:import './font-awesome'; - In
index.jsat root,import './lib';(if you don't have).
Animate.css
Install and configure
yarn add animate.css- In
lib/tạoanimate-css.jsvà thêmimport 'animate.css'; - In
index.js, import bằngimport './animate-css';
Custom duration time
- Tùy chỉnh thời gian animation bằng scss config trong
style/: - Tạo file
_animate.scssnhư source code - In
index.scss:@import './animate.scss'; - File này sẽ tạo ra các class sau:
.animated.duration-100
.animated.duration-200
...
.animated.duration-1100
.animated.duration-1200
...
.animated.duration-3000
How to use
Example:
<!-- In/Out default -->
<div class="animated slideInUp">ABCDEFGHIJKLMNOP</div>
<div class="animated slideOut" >ABCDEFGHIJKLMNOP</div>
<div class="animated fadeInDown" >ABCDEFGHIJKLMNOP</div>
<!-- In/Out custom duration -->
<div class="animated fadeInUp duration-500" >ABCDEFGHIJKLMNOP</div>
<div class="animated flipIn duration-1000" >ABCDEFGHIJKLMNOP</div>
<div class="animated slideOutDown duration-700" >ABCDEFGHIJKLMNOP</div>
<!-- Infinite default/custom duration -->
<div class="animated flash infinite" >ABCDEFGHIJKLMNOP</div>
<div class="animated flash infinite duration-1200" >ABCDEFGHIJKLMNOP</div>
Demo
- View demo at component
DemoAnimateCss - View Demo here
- View Implementation here
react-router-dom (router)
react-router-dom được sử dụng cho 1 Single Page Application (SPA).- In terminal:
yarn add react-router-dom - Bạn xem implement trong
components/layout/body - Cũng có thể xem ở
components/pages/demo-react-router - Documents is available at React Router Dom
react-loadable (code-splitting)
code-splitting là một kỹ thuật tăng tốc độ của single page app. Nó sẽ lazy loading, tức chờ cho điến khi người dùng click vào component đó nó mới thực sự load component đó lên. Điều này giúp ứng dụng của ta load nhanh ở lần chạy đầu tiên khi người dùng chưa cần vào các component này.
create-react-app cũng hỗ trợ ta trong việc code-splitting, do đó ta không nên bỏ qua kỹ thuật này,
Installation, Usage
react-loadable hỗ trợ code-splitting:create-react-appsẽ bundle script file mới, khi được gọi, nó mới load file này.
- In terminal:
yarn add react-loadable react-router-dom - Tạo 1 Loading component (view components/common/loading/)
- Khi sử dụng Loadable với loading component, các thuộc tính cần quan tâm cho component này:
{ isLoading: true, pastDelay: false, timedOut: false, error: null } - View
components/page/demo-loadable-componentto sample implement. - Component
DemoLoadableComponent(is not loadable) andLoadableDemoComponent(is loadable)
Test Loadable Components - code-splitting
- Inspect element trong trình duyệt
- Chọn tab network
- Click filter JS
- Refresh page
- lúc đầu chỉ thấy file
bundle.jsvà 1 số file js khác. - Click component hỗ trợ loadable, ta sẽ thấy
*.chunk.jsis loaded. Đây là lazy loading component - View Demo here
- View Implementation here
react-intl - API cho format date, number and string
Internationalize React apps. Thư viện này cung cấp các React components and API để format dates, numbers, and strings, bao gồm pluralization (số nhiều) và handling translations (chuyến đổi).
Features - các tính năng
- Display numbers with separators.
- Display dates and times correctly.
- Display dates relative to "now".
- Pluralize labels in strings.
- Support for 150+ languages.
- Runs in the browser and Node.js.
- Built on standards.
Document
You can view document at here: https://github.com/yahoo/react-intl
Usage in this tutorial
- In
index.js, ta import và dùng provider cho App component:
import { IntlProvider } from 'react-intl';
ReactDOM.render(
<Provider store={store}>
<IntlProvider locale="en">
<App />
</IntlProvider>
</Provider>,
document.getElementById('root')
);
- Trong tứng component, ta import component of
react-intlđể sử dụng. Bạn có thể xem demo sử dụng ở demo phần redux.
Redux: redux, react-redux, redux-thunk
Redux là 1 kỹ thuật ta không thể bỏ qua khi làm việc với react.
Installation
yarn add redux react-redux redux-thunkUsage
- In
src, tạo:actions/action-types.js: định nghĩa tên actionactions/index.js: định nghĩa các actionreducers/: khai báo các reducerreducers/[name].js: định nghĩa các action cụ thể.reducers/index.js: combine các reducer của redux, sau đó sẽ được createStore.
- In
index.js:import { Provider } from 'react-redux';: dùng Provider để store reduximport { createStore, applyMiddleware } from 'redux';: dùng createStore và middlewarethunkcho createStoreimport thunk from 'redux-thunk';: middleware cho createStore, support async functionimport allReducers from './reducers';: reducers sau khi combinedconst store = createStore(allReducers, applyMiddleware(thunk));: createStore với combined reducer, và apply middleware thunk- Hiện tại bạn không cần quan tâm reducers
Users, ta sẽ sử dụng cái này sau.
- In
reducers/index.js: combine reducers:- In this tutorial, I demo with Items and Users (users is used for other section demo).
import { combineReducers } from 'redux';
import Items from './items';
import Users from './users';
const reducers = combineReducers({
Items,
Users
});
export default reducers;
Fetch Data API to server node
Create services to get API
mkdir src/services(if you have not)touch db-service.js auth-service.js(db- to get database, auth- to authentication user)- Example with
db-service.js:import Env from './../environments';: to getbaseUrlwith environmentsexport default class DbServiceas static class- set baseUrl to get API:
static baseUrl() { return Env.baseUrl; }
static parseUrl(url) { return DbService.baseUrl() + url; }
Example
get API:static getItems = () => {
let url = DbService.parseUrl('/api/items');
console.log(url);
return fetch(url).then(res => res.json());
}
Example
Post API: static addItem = (item) => {
let url = DbService.parseUrl('/api/items');
return fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(item)
}).then(res => res.json());
}
UI Awesome with React Component
Reveal Component on scroll: use react-reveal
Tạo animation khi người dụng scroll tới element. Khá hữu ích.
Installation
yarn add react-revealSupport
Reveal with React
Fade
Flip
Rotate
Zoom
Bounce
Slide
Roll
left/right/top/bottom
fadeOut
Animated.css with React
Jump
Flash
HeadShake
Jello
Pulse
RubberBand
Shake
Spin
Swing
Tada
How to use?
- View demo with component
DemoReactReveal.
Scroll animted to target - react-scrollchor
Tạo animation khi người dùng click và chuyên tới 1 element nào đó.
Installation
yarn add react-scrollchorHow to use?
- View demo with component
DemoReactScrollchor.
Datatable with react-table
- Xem demo: Demo
- Xem implementation trong
demo-react-table- Implementation - Ta dùng
react-tablewith features:- Lightweight at 11kb (and just 2kb more for styles)
- Fully customizable (JSX, templates, state, styles, callbacks)
- Client-side & Server-side pagination
- Multi-sort
- Filters
- Pivoting & Aggregation
- Minimal design & easily themeable
- Fully controllable via optional props and callbacks
- Mình cũng dùng thêm
react-selectvàreact-datepickervớimoment. You can view docs for these package here:
VS Code Extensions
Làm việc với react thì không thể thiếu các extension cần thiết nếu bạn đang sử dụng visual studio code (VS Code)
Các bạn chỉ đơn giản install extension và config nếu cần thiết.
Icons, Colors, View
Snippets
- ES7 React/Redux/GraphQL/React-Native snippets
- JavaScript (ES6) code snippets
- Bootstrap 3 Snippets
- Bootstrap 4 & Font awesome snippets
- Font-awesome codes for html
- Font-awesome codes for css
- HTML Snippets
- HTML CSS suppport
Intellisence
- npm
- npm Intellisence
- Path Intellisense
- SCSS IntelliSence
- Auto Close Tag
- Auto Rename Tag
- IntelliSense for CSS class names
Lint Code, Formater
- Prettier - Code formatter
- EditorConfig for VS Code
- ESLint
- TSLint
- Sass
- Sass Formatter
- Beautify css/sass/scss/less
Edit, Preview README - Markdown files
VS Code User Settings
Cũng nên setting một số config cho VS Code, tạo nên coding style chuẩn:
- Enter
Ctrl + Shift P - Search
user settings - Choose
Preferences: Open User Settingsand enter. - Edit your file
User Settingsby following lines: (you can search inDefault Settingsand customize your style)
{
"workbench.iconTheme": "vscode-icons",
"workbench.startupEditor": "newUntitledFile",
"window.zoomLevel": 0,
"editor.fontSize": 13,
"eslint.autoFixOnSave": true,
"tslint.autoFixOnSave": true,
"editor.formatOnSave": false,
"editor.renderWhitespace": "boundary",
"editor.quickSuggestions": {
"other": true,
"comments": true,
"strings": true
},
"terminal.integrated.cursorStyle": "line",
"terminal.integrated.fontSize": 13,
"terminal.integrated.fontFamily": "",
"vsicons.projectDetection.autoReload": true,
}
By: viblo.asia
0 nhận xét:
Post a Comment