詳解如何用webpack4從零開始構(gòu)建react開發(fā)環(huán)境
項目文件準(zhǔn)備:
執(zhí)行npm init,然后創(chuàng)建如下圖所示的文件。

在index.html里面添加
<!DOCTYPE html> <html> <head> <title>The Minimal React Webpack Babel Setup</title> </head> <body> <div id="app"></div> <script src="./bundle.js"></script> </body> </html>
在webpack.config.js里面添加
module.exports = {
entry: './src/index.js',
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './dist'
}
};
在package.json里面添加
"scripts": {
"start": "webpack-dev-server --config ./webpack.config.js --mode development"
},
這樣,當(dāng)執(zhí)行npm start的時候,就會使用webpack-dev-server把index.js相關(guān)文件打包,生成bundle.js,這時候瀏覽器會打開一個窗口,執(zhí)行index.html(contentBase里面定義了),又因為index.html里面引入了bundle.js,就可以把壓縮后的js文件執(zhí)行起來。當(dāng)然引入bundle.js這一步可以由我們強大的html-webpack-plugin完成。
安裝依賴
npm install --save-dev webpack webpack-dev-server webpack-cli npm install --save-dev @babel/core @babel/preset-env npm install --save-dev babel-loader npm install --save-dev @babel/preset-react
配置babel
在根目錄下新建.babelrc文件,然后添加
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}
在webpack.config.js里面添加babel-loader配置
module.exports = {
...
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
}
...
};
引入react
npm install --save react react-dom
修改index.js: 這個ReactDOM.render就是把元素渲染到index.html里面id為'app'的元素廈門。在實際開發(fā)中,我們會把app.js渲染到這里,然后在app.js里面寫redux,react-router構(gòu)成的頁面的起點。
import React from 'react';
import ReactDOM from 'react-dom';
const title = 'My Minimal React Webpack Babel Setup';
ReactDOM.render(
<div>{title}</div>,
document.getElementById('app')
);
配置react熱加載
npm install --save-dev react-hot-loader
webpack.config.js
const webpack = require('webpack');
module.exports = {
...
plugins: [
new webpack.HotModuleReplacementPlugin()
],
devServer: {
contentBase: './dist',
hot: true
}
...
};
修改index.js
import React from 'react';
import ReactDOM from 'react-dom';
const title = 'My Minimal React Webpack Babel Setup';
ReactDOM.render(
<div>{title}</div>,
document.getElementById('app')
);
+ module.hot.accept();
這個時候執(zhí)行npm start,就可以在瀏覽器訪問http://localhost:8080看到Index.html里面的內(nèi)容啦啦。參考鏈接:
https://www.robinwieruch.de/minimal-react-webpack-babel-setup/#babel-react-setup
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React中useEffect與生命周期鉤子函數(shù)的對應(yīng)關(guān)系說明
這篇文章主要介紹了React中useEffect與生命周期鉤子函數(shù)的對應(yīng)關(guān)系說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09
解析TypeError:import_react_native.AppState.removeEventListener
這篇文章主要為大家介紹了TypeError:import_react_native.AppState.removeEventListener?is?not?a?function問題解決分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09

