面對(duì)日新月異的前端,我表示快學(xué)不動(dòng)了:joy:。 Webpack 老早就已經(jīng)更新到了 V4.x,前段時(shí)間 React 又推出了 hooks API。剛好春節(jié)在家里休假,時(shí)間比較空閑,還是趕緊把 React 技術(shù)棧這塊補(bǔ)上。
網(wǎng)上有很多介紹 hooks 知識(shí)點(diǎn)的文章,但都比較零碎,基本只能寫一些小 Demo 。還沒有比較系統(tǒng)的,全新的基于 hooks 進(jìn)行搭建實(shí)際項(xiàng)目的講解。所以這里就從開發(fā)實(shí)際項(xiàng)目的角度,搭建起單頁面 Web App 項(xiàng)目的基本腳手架,并基于 hooks API 實(shí)現(xiàn)一個(gè) react 項(xiàng)目模版。
Hooks最吸引人的地方就是用 函數(shù)式組件 代替面向?qū)ο蟮?類組件 。此前的 react 如果涉及到狀態(tài),解決方案通常只能使用 類組件 ,業(yè)務(wù)邏輯一復(fù)雜就容易導(dǎo)致組件臃腫,模塊的解藕也是個(gè)問題。而使用基于 hooks 的 函數(shù)組件 后,代碼不僅更加簡(jiǎn)潔,寫起來更爽,而且模塊復(fù)用也方便得多,非??春盟奈磥怼?/p>
webpack 4 的配置
沒有使用 create-react-app 這個(gè)腳手架,而是從頭開始配置開發(fā)環(huán)境,因?yàn)檫@樣自定義配置某些功能會(huì)更方便些。下面這個(gè)是通用的配置 webpack.common.js 文件。
const { resolve } = require('path');const HtmlWebpackPlugin = require('html-webpack-plugin');const CleanWebpackPlugin = require('clean-webpack-plugin');const { HotModuleReplacementPlugin } = require('webpack');module.exports = { entry: './src/index.js',//單入口 output: { path: resolve(__dirname, 'dist'), filename: '[name].[hash].js'//輸出文件添加hash }, optimization: { // 代替commonchunk, 代碼分割 runtimeChunk: 'single', splitChunks: { cacheGroups: { vendor: { test: /[///]node_modules[///]/, name: 'vendors', chunks: 'all' } } } }, module: { rules: [ { test: //.jsx?$/, exclude: /node_modules/, use: ['babel-loader'] }, { test: //.css$/, use: ['style-loader', 'css-loader'] }, { test: //.scss$/, use: ['style-loader', { loader: 'css-loader', options: { importLoaders: 1, modules: true,//css modules localIdentName: '[name]___[local]___[hash:base64:5]' }, }, 'postcss-loader', 'sass-loader'] }, { /* 當(dāng)文件體積小于 limit 時(shí),url-loader 把文件轉(zhuǎn)為 Data URI 的格式內(nèi)聯(lián)到引用的地方 當(dāng)文件大于 limit 時(shí),url-loader 會(huì)調(diào)用 file-loader, 把文件儲(chǔ)存到輸出目錄,并把引用的文件路徑改寫成輸出后的路徑 */ test: //.(png|jpg|jpeg|gif|eot|ttf|woff|woff2|svg|svgz)(/?.+)?$/, use: [{ loader: 'url-loader', options: { limit: 1000 } }] } ] }, plugins: [ new CleanWebpackPlugin(['dist']),//生成新文件時(shí),清空生出目錄 new HtmlWebpackPlugin({ template: './public/index.html',//模版路徑 favicon: './public/favicon.png', minify: { //壓縮 removeAttributeQuotes:true, removeComments: true, collapseWhitespace: true, removeScriptTypeAttributes:true, removeStyleLinkTypeAttributes:true }, }), new HotModuleReplacementPlugin()//HMR ]};
新聞熱點(diǎn)
疑難解答
圖片精選