使用webpack搭建react開發(fā)環(huán)境的方法
1.初始化項目
mkdir react-redux && cd react-redux npm init -y
2.安裝webpack
npm i webpack -D
npm i -D 是 npm install --save-dev 的簡寫,是指安裝模塊并保存到 package.json 的 devDependencies中,主要在開發(fā)環(huán)境中的依賴包. 如果使用webpack 4+ 版本,還需要安裝 CLI。
npm install -D webpack webpack-cli
3.新建一下項目結(jié)構(gòu)
react-redux |- package.json + |- /dist + |- index.html |- /src |- index.js
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="root"></div> <script src="bundle.js"></script> </body> </html>
index.js
document.querySelector('#root').innerHTML = 'webpack使用';
非全局安裝下的打包。
node_modules\.bin\webpack src\index.js --output dist\bundle.js --mode development
打開dist目錄下的html顯示 webpack使用
配置webpack
1.使用配置文件
const path=require('path');
module.exports={
entry:'./src/index.js',
output:{
filename:'bundle.js',
path:path.resolve(__dirname,'dist')
}
};
運行命令: node_modules\.bin\webpack --mode production 可以以進行打包 2.NPM 腳本(NPM Scripts) 在在 package.json 添加一個 npm 腳本(npm script): "build": "webpack --mode production" 運行 npm run build 即可打包
使用webpack構(gòu)建本地服務(wù)器
webpack-dev-server 提供了一個簡單的 web 服務(wù)器,并且能夠?qū)崟r重新加載。
1.安裝 npm i -D webpack-dev-server 修改配置文件webpack.config.js
const path=require('path');
module.exports={
entry:'./src/index.js',
output:{
filename:'bundle.js',
path:path.resolve(__dirname,'dist')
},
//以下是新增的配置
devServer:{
contentBase: "./dist",//本地服務(wù)器所加載的頁面所在的目錄
historyApiFallback: true,//不跳轉(zhuǎn)
inline: true,//實時刷新
port:3000,
open:true,//自動打開瀏覽器
}
};
運行 webpack-dev-server --progress ,瀏覽器打開localhost:3000,修改代碼會實時顯示修改的結(jié)果. 添加scripts腳本,運行 npm start 自動打開 http://localhost:8080/
"start": "webpack-dev-server --open --mode development"
啟動webpack-dev-server后,在目標文件夾中是看不到編譯后的文件的,實時編譯后的文件都保存到了內(nèi)存當中。因此使用webpack-dev-server進行開發(fā)的時候都看不到編譯后的文件
2.熱更新
配置一個webpack自帶的插件并且還要在主要js文件里檢查是否有module.hot
plugins:[
//熱更新,不是刷新
new webpack.HotModuleReplacementPlugin()
],
在主要js文件里添加以下代碼
if (module.hot){
//實現(xiàn)熱更新
module.hot.accept();
}
在webpack.config.js中開啟熱更新
devServer:{
contentBase: "./dist",//本地服務(wù)器所加載的頁面所在的目錄
historyApiFallback: true,//不跳轉(zhuǎn)
inline: true,//實時刷新
port:3000,
open:true,//自動打開瀏覽器
hot:true //開啟熱更新
},
熱更新允許在運行時更新各種模塊,而無需進行完全刷新.
配置Html模板
1.安裝html-webpack-plugin插件
npm i html-webpack-plugin -D
2.在webpack.config.js里引用插件
const path=require('path');
let webpack=require('webpack');
let HtmlWebpackPlugin=require('html-webpack-plugin');
module.exports={
entry:'./src/index.js',
output:{
//添加hash可以防止文件緩存,每次都會生成4位hash串
filename:'bundle.[hash:4].js',
path:path.resolve('dist')
},
//以下是新增的配置
devServer:{
contentBase: "./dist",//本地服務(wù)器所加載的頁面所在的目錄
historyApiFallback: true,//不跳轉(zhuǎn)
inline: true,//實時刷新
port:3000,
open:true,//自動打開瀏覽器
hot:true //開啟熱更新
},
plugins:[
new HtmlWebpackPlugin({
template:'./src/index.html',
hash:true, //會在打包好的bundle.js后面加上hash串
})
]
};
運行 npm run build 進行打包,這時候每次npm run build的時候都會在dist目錄下創(chuàng)建很多打好的包.應(yīng)該每次打包之前都將dist目錄下的文件清空,再把打包好的文件放進去,這里使用clean-webpack-plugin插件.通過 npm i clean-webpack-plugin -D 命令安裝.然后在webpack.config.js中引用插件.
const path=require('path');
let webpack=require('webpack');
let HtmlWebpackPlugin=require('html-webpack-plugin');
let CleanWebpackPlugin=require('clean-webpack-plugin');
module.exports={
entry:'./src/index.js',
output:{
//添加hash可以防止文件緩存,每次都會生成4位hash串
filename:'bundle.[hash:4].js',
path:path.resolve('dist')
},
//以下是新增的配置
devServer:{
contentBase: "./dist",//本地服務(wù)器所加載的頁面所在的目錄
historyApiFallback: true,//不跳轉(zhuǎn)
inline: true,//實時刷新
port:3000,
open:true,//自動打開瀏覽器
hot:true //開啟熱更新
},
plugins:[
new HtmlWebpackPlugin({
template:'./src/index.html',
hash:true, //會在打包好的bundle.js后面加上hash串
}),
//打包前先清空
new CleanWebpackPlugin('dist')
]
};
之后打包便不會產(chǎn)生多余的文件.
編譯es6和jsx
1.安裝babel npm i babel-core babel-loader babel-preset-env babel-preset-react babel-preset-stage-0 -D babel-loader: babel加載器 babel-preset-env : 根據(jù)配置的 env 只編譯那些還不支持的特性。 babel-preset-react: jsx 轉(zhuǎn)換成js
2.添加.babelrc配置文件
{
"presets": ["env", "stage-0","react"] //從左向右解析
}
3.修改webpack.config.js
const path=require('path');
module.exports={
entry:'./src/index.js',
output:{
filename:'bundle.js',
path:path.resolve(__dirname,'dist')
},
//以下是新增的配置
devServer:{
contentBase: "./dist",//本地服務(wù)器所加載的頁面所在的目錄
historyApiFallback: true,//不跳轉(zhuǎn)
inline: true//實時刷新
},
module:{
rules:[
{
test:/\.js$/,
exclude:/(node_modules)/, //排除掉nod_modules,優(yōu)化打包速度
use:{
loader:'babel-loader'
}
}
]
}
};
開發(fā)環(huán)境與生產(chǎn)環(huán)境分離
1.安裝 webpack-merge
npm install --save-dev webpack-merge
2.新建一個名為webpack.common.js文件作為公共配置,寫入以下內(nèi)容:
const path=require('path');
let webpack=require('webpack');
let HtmlWebpackPlugin=require('html-webpack-plugin');
let CleanWebpackPlugin=require('clean-webpack-plugin');
module.exports={
entry:['babel-polyfill','./src/index.js'],
output:{
//添加hash可以防止文件緩存,每次都會生成4位hash串
filename:'bundle.[hash:4].js',
path:path.resolve(__dirname,'dist')
},
plugins:[
new HtmlWebpackPlugin({
template:'./src/index.html',
hash:true, //會在打包好的bundle.js后面加上hash串
}),
//打包前先清空
new CleanWebpackPlugin('dist'),
new webpack.HotModuleReplacementPlugin() //查看要修補(patch)的依賴
],
module:{
rules:[
{
test:/\.js$/,
exclude:/(node_modules)/, //排除掉nod_modules,優(yōu)化打包速度
use:{
loader:'babel-loader'
}
}
]
}
};
3.新建一個名為webpack.dev.js文件作為開發(fā)環(huán)境配置
const merge=require('webpack-merge');
const path=require('path');
let webpack=require('webpack');
const common=require('./webpack.common.js');
module.exports=merge(common,{
devtool:'inline-soure-map',
mode:'development',
devServer:{
historyApiFallback: true, //在開發(fā)單頁應(yīng)用時非常有用,它依賴于HTML5 history API,如果設(shè)置為true,所有的跳轉(zhuǎn)將指向index.html
contentBase:path.resolve(__dirname, '../dist'),//本地服務(wù)器所加載的頁面所在的目錄
inline: true,//實時刷新
open:true,
compress: true,
port:3000,
hot:true //開啟熱更新
},
plugins:[
//熱更新,不是刷新
new webpack.HotModuleReplacementPlugin(),
],
});
4.新建一個名為webpack.prod.js的文件作為生產(chǎn)環(huán)境配置
const merge = require('webpack-merge');
const path=require('path');
let webpack=require('webpack');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode:'production',
plugins: [
new UglifyJSPlugin()
]
});
配置react
1.安裝react、
react-dom npm i react react-dom -S
2.新建App.js,添加以下內(nèi)容.
import React from 'react';
class App extends React.Component{
render(){
return (<div>佳佳加油</div>);
}
}
export default App;
3.在index.js添加以下內(nèi)容.
import React from 'react';
import ReactDOM from 'react-dom';
import {AppContainer} from 'react-hot-loader';
import App from './App';
ReactDOM.render(
<AppContainer>
<App/>
</AppContainer>,
document.getElementById('root')
);
if (module.hot) {
module.hot.accept();
}
4.安裝 react-hot-loader
npm i -D react-hot-loader
5.修改配置文件 在 webpack.config.js 的 entry 值里加上 react-hot-loader/patch,一定要寫在entry 的最前面,如果有 babel-polyfill 就寫在babel-polyfill 的后面
6.在 .babelrc 里添加 plugin, "plugins": ["react-hot-loader/babel"]
處理SASS
1.安裝 style-loader css-loader url-loader
npm install style-loader css-loader url-loader --save-dev
2.安裝 sass-loader node-sass
npm install sass-loader node-sass --save-dev
3.安裝 mini-css-extract-plugin ,提取單獨打包css文件
npm install --save-dev mini-css-extract-plugin
4.配置webpack配置文件
webpack.common.js
{
test:/\.(png|jpg|gif)$/,
use:[
"url-loader"
]
},
webpack.dev.js
{
test:/\.scss$/,
use:[
"style-loader",
"css-loader",
"sass-loader"
]
}
webpack.prod.js
const merge = require('webpack-merge');
const path=require('path');
let webpack=require('webpack');
const MiniCssExtractPlugin=require("mini-css-extract-plugin");
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode:'production',
module:{
rules:[
{
test:/\.scss$/,
use:[
// fallback to style-loader in development
process.env.NODE_ENV !== 'production' ? 'style-loader' : MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader"
]
}
]
},
plugins: [
new UglifyJSPlugin(),
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "[name].css",
chunkFilename: "[id].css"
})
]
});
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- 詳解使用WebPack搭建React開發(fā)環(huán)境
- 基于Webpack4和React hooks搭建項目的方法
- 基于webpack4.X從零搭建React腳手架的方法步驟
- Webpack 4.x搭建react開發(fā)環(huán)境的方法步驟
- webpack4 + react 搭建多頁面應(yīng)用示例
- 基于webpack4搭建的react項目框架的方法
- 從零開始搭建webpack+react開發(fā)環(huán)境的詳細步驟
- 手動用webpack搭建第一個ReactApp的示例
- 詳解基于webpack搭建react運行環(huán)境
- 使用webpack5從0到1搭建一個react項目的實現(xiàn)步驟
相關(guān)文章
React Native 混合開發(fā)多入口加載方式詳解
這篇文章主要介紹了React Native 混合開發(fā)多入口加載方式詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-09-09
React18使用Echarts和MUI實現(xiàn)一個交互性的溫度計
這篇文章我們將結(jié)合使用React 18、Echarts和MUI(Material-UI)庫,展示如何實現(xiàn)一個交互性的溫度計,感興趣的小伙伴可以跟隨小編一起學習一下2024-01-01
如何解決React官方腳手架不支持Less的問題(小結(jié))
這篇文章主要介紹了如何解決React官方腳手架不支持Less的問題(小結(jié)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-09-09
ReactQuery系列React?Query?實踐示例詳解
這篇文章主要為大家介紹了ReactQuery系列React?Query?實踐示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11
react-router browserHistory刷新頁面404問題解決方法
本篇文章主要介紹了react-router browserHistory刷新頁面404問題解決方法,非常具有實用價值,需要的朋友可以參考下2017-12-12

