這篇文章將為大家詳細(xì)講解有關(guān)基于webpack4.X從零搭建React腳手架的案例,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
建網(wǎng)站原本是網(wǎng)站策劃師、網(wǎng)絡(luò)程序員、網(wǎng)頁(yè)設(shè)計(jì)師等,應(yīng)用各種網(wǎng)絡(luò)程序開(kāi)發(fā)技術(shù)和網(wǎng)頁(yè)設(shè)計(jì)技術(shù)配合操作的協(xié)同工作。創(chuàng)新互聯(lián)專(zhuān)業(yè)提供網(wǎng)站設(shè)計(jì)制作、網(wǎng)站建設(shè),網(wǎng)頁(yè)設(shè)計(jì),網(wǎng)站制作(企業(yè)站、成都響應(yīng)式網(wǎng)站建設(shè)公司、電商門(mén)戶(hù)網(wǎng)站)等服務(wù),從網(wǎng)站深度策劃、搜索引擎友好度優(yōu)化到用戶(hù)體驗(yàn)的提升,我們力求做到極致!項(xiàng)目初始化
$ npm init
安裝webpack
本次創(chuàng)建是基于webpack4
$ npm install --save-dev
新建webpack配置文件
在根目錄創(chuàng)建build文件夾,添加一個(gè)js文件,命名為webpack.base.conf.js
// webpack.base.conf.js 文件 const path = require('path'); const DIST_PATH = path.resolve(__dirname, '../dist'); module.exports = { entry: { app: './app/index.js' }, output: { filename: "js/bundle.js", path: DIST_PATH } };
使用merge的方式來(lái)組織webpack基礎(chǔ)配置和不同環(huán)境的配置
先安裝webpack-merge:
$ npm install --save-dev webpack-merge
在build文件夾中再添加一個(gè)js文件,命名為 webpack.prod.conf.js
// webpack.prod.conf.js 文件 const merge = require('webpack-merge'); const baseWebpackConfig = require('./webpack.base.conf'); module.exports = merge(baseWebpackConfig, { mode: 'production' });
在根目錄下創(chuàng)建app目錄,然后創(chuàng)建index.js文件
var element =document.getElementById('root'); element.innerHTML = 'hello, world!';
在根目錄創(chuàng)建一個(gè)public文件夾,然后新建一個(gè)index.html文件
// index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>從零開(kāi)始搭建react工程</title> </head> <body> <div id="root"></div> <script src="../dist/js/bundle.js"></script> </body> </html>
當(dāng)前項(xiàng)目目錄樹(shù)
|- /app |- index.js |- /node_modules |- /public |- index.html |- /build |- webpack.base.conf.js |- webpack.prod.conf.js |- package.json |- package-lock.json
安裝webpack-cli
webpack 4.0 版本之后的webpack,已經(jīng)將webpack命令工具遷移到webpack-cli模塊了,需要安裝 webpack-cli
$ npm install --save-dev webpack-cli
package.json文件 scripts屬性配置一個(gè)build命令
其值為:webpack --config build/webpack.prod.conf.js,以下是scripts的相關(guān)代碼
// package.json "scripts": { "build": "webpack --config build/webpack.prod.conf.js", "test": "echo \"Error: no test specified\" && exit 1" },
安裝React
$ npm install --save react react-dom
修改app目錄下的index.js的代碼
import React from "react"; import ReactDom from "react-dom"; ReactDom.render( <h2>hello, world!</h2>, document.getElementById("root") );
注意 import 屬于ES6規(guī)范,因此需要轉(zhuǎn)譯ES2015+的語(yǔ)法,安裝并配置 babel 以及相關(guān)依賴(lài)
$ npm install --save-dev babel-loader babel-core babel-preset-env babel-preset-react
根目錄創(chuàng)建.babelrc文件,配置presets.
{ "presets": [ [ "env", { "targets": { "browsers": [ "> 1%", "last 5 versions", "ie >= 8" ] } } ], "react" ] }
修改webpack.base.conf.js文件
// webpack.base.conf.js const path = require('path'); const APP_PATH = path.resolve(__dirname, '../app'); const DIST_PATH = path.resolve(__dirname, '../dist'); module.exports = { entry: { app: './app/index.js' }, output: { filename: 'js/bundle.js', path: DIST_PATH }, module: { rules: [ { test: /\.js?$/, use: "babel-loader", include: APP_PATH } ] } };
運(yùn)行 npm run build
添加插件
public下的index.html本該自動(dòng)添加到dist目錄,并且引用資源自動(dòng)加載到該文件,通過(guò)html-webpack-plugin實(shí)現(xiàn)這一步
$ npm install html-webpack-plugin --save-dev
webpack.prod.conf.js中配置plugins屬性
const merge = require('webpack-merge'); const baseWebpackConfig = require('./webpack.base.conf.js'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = merge(baseWebpackConfig, { mode: 'production', plugins: [ new HtmlWebpackPlugin({ template: 'public/index.html', inject: 'body', minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }, }) ] });
刪除 index.html 中手動(dòng)引入的 script 標(biāo)簽
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>從零開(kāi)始搭建react工程</title> </head> <body> <div id="root"></div> </body> </html>
重新編譯查看 npm run build 瀏覽器打開(kāi)查看目錄 dist 下的 index.html
以上步驟都成功的前提下繼續(xù)走下一步
生成的文件名添加Hash值,目的是解決緩存問(wèn)題
修改webpack.prod.conf.js,mode: 'production', 增加以下代碼
// webpack.prod.conf.js output: { filename: "js/[name].[chunkhash:16].js", },
生成前需要清理之前項(xiàng)目生成的文件,因?yàn)橛捎谖募母淖內(nèi)绻粍h除會(huì)一直增加
安裝插件 clean-webpack-plugin
$ npm install --save-dev clean-webpack-plugin
修改 webpack.prod.conf.js
// webpack.prod.conf.js const merge = require('webpack-merge'); const baseWebpackConfig = require('./webpack.base.conf.js'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); module.exports = merge(baseWebpackConfig, { mode: 'production', output: { filename: "js/[name].[chunkhash:16].js", }, plugins: [ new HtmlWebpackPlugin({ template: 'public/index.html', inject: 'body', minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }, }), new CleanWebpackPlugin(['../dist'], { allowExternal: true }) ] });
公共代碼與業(yè)務(wù)代碼分離
修改 webpack.base.conf.js 的 entry 入口屬性,抽出框架代碼
entry: { app: './app/index.js', framework: ['react','react-dom'], },
修改webpack.prod.conf.js,增加以下代碼,目的是分離框架代碼和業(yè)務(wù)代碼
雖然上面步驟抽出框架代碼生成兩個(gè)文件,但是app.js還是包含框架代碼
optimization: { splitChunks: { chunks: "all", minChunks: 1, minSize: 0, cacheGroups: { framework: { test: "framework", name: "framework", enforce: true } } } }
cacheGroups對(duì)象,定義了需要被抽離的模塊
其中test屬性是比較關(guān)鍵的一個(gè)值,他可以是一個(gè)字符串,也可以是正則表達(dá)式,還可以是函數(shù)。如果定義的是字符串,會(huì)匹配入口模塊名稱(chēng),會(huì)從其他模塊中把包含這個(gè)模塊的抽離出來(lái)
name是抽離后生成的名字,和入口文件模塊名稱(chēng)相同,這樣抽離出來(lái)的新生成的framework模塊會(huì)覆蓋被抽離的framework模塊
整合 webpack-dev-server
開(kāi)發(fā)環(huán)境開(kāi)啟服務(wù)監(jiān)聽(tīng)文件改動(dòng)實(shí)時(shí)更新最新內(nèi)容
$ npm install --save-dev webpack-dev-server
在build中添加webpack.dev.conf.js文件
const path = require('path'); const merge = require('webpack-merge'); const baseWebpackConfig = require('./webpack.base.conf.js'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const webpack = require('webpack'); module.exports = merge(baseWebpackConfig, { mode: 'development', output: { filename: "js/[name].[hash:16].js", }, plugins: [ new HtmlWebpackPlugin({ template: 'public/index.html', inject: 'body', minify: { html5: true }, hash: false }), new webpack.HotModuleReplacementPlugin() ], devServer: { port: '8080', contentBase: path.join(__dirname, '../public'), compress: true, historyApiFallback: true, hot: true, https: false, noInfo: true, open: true, proxy: {} } });
在package.json scripts屬性添加內(nèi)容
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
npm run dev
自動(dòng)打開(kāi)瀏覽器打開(kāi)入口頁(yè)面實(shí)時(shí)更新
獨(dú)立導(dǎo)出 css 文件
安裝css相關(guān)依賴(lài)
sass less 預(yù)處理
$ npm install extract-text-webpack-plugin $ npm install style-loader css-loader postcss-loader autoprefixer --save-dev $ npm install less sass less-loader sass-loader stylus-loader node-sass --save-dev
webpack.base.conf.js 文件修改
// webpack.base.conf.js { test: /\.css$/, use: [ { loader: "style-loader" //在html中插入<style>標(biāo)簽 }, { loader: "css-loader",//獲取引用資源,如@import,url() }, { loader: "postcss-loader", options: { plugins:[ require('autoprefixer')({ browsers:['last 5 version'] }) ] } } ] }, { test:/\.less$/, use: [ { loader: "style-loader" }, { loader: "css-loader" }, { loader: "postcss-loader",//自動(dòng)加前綴 options: { plugins:[ require('autoprefixer')({ browsers:['last 5 version'] }) ] } }, { loader: "less-loader" } ] }, { test:/\.scss$/, use:[ { loader: "style-loader" }, { loader: "css-loader", }, { loader: "sass-loader" }, { loader: "postcss-loader", options: { plugins:[ require('autoprefixer')({ browsers:['last 5 version'] }) ] } } ] },
圖片和路徑處理
$ npm i file-loader url-loader --save-dev
webpack.base.conf.js 文件修改
// webpack.base.conf.js { test: /\.(png|jpg|gif|woff|svg|eot|woff2|tff)$/, use: 'url-loader?limit=8129', //注意后面那個(gè)limit的參數(shù),當(dāng)你圖片大小小于這個(gè)限制的時(shí)候,會(huì)自動(dòng)啟用base64編碼圖片 exclude: /node_modules/ }
build 時(shí)報(bào)錯(cuò)
Error: Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead
at Chunk.get (F:\react\createApp\node_modules\webpack\lib\Chunk.js:824:9)
webpack4.0中使用“extract-text-webpack-plugin”報(bào)錯(cuò)
解決辦法
$ npm install extract-text-webpack-plugin@next
背景圖片路徑問(wèn)題
由于css文件分離出來(lái)的原因,會(huì)導(dǎo)致在css文件夾下找images文件夾下的圖片
解決辦法 publicPath屬性改為 '/',以絕對(duì)路徑的方式尋找資源
{ test:/\.(png|jpg|gif)$/, use:[{ loader:'url-loader', options: { // outputPath:'../',//輸出**文件夾 publicPath: '/', name: "images/[name].[ext]", limit:500 //是把小于500B的文件打成Base64的格式,寫(xiě)入JS } }] },
關(guān)于“基于webpack4.X從零搭建React腳手架的案例”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
當(dāng)前題目:基于webpack4.X從零搭建React腳手架的案例-創(chuàng)新互聯(lián)
URL分享:http://m.rwnh.cn/article40/iigeo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、外貿(mào)建站、網(wǎng)站營(yíng)銷(xiāo)、響應(yīng)式網(wǎng)站、定制網(wǎng)站、Google
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容