執行npm init,而後建立以下圖所示的文件。
html
在index.html裏面添加node
<!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裏面添加react
module.exports = { entry: './src/index.js', output: { path: __dirname + '/dist', publicPath: '/', filename: 'bundle.js' }, devServer: { contentBase: './dist' } };
在package.json裏面添加webpack
"scripts": { "start": "webpack-dev-server --config ./webpack.config.js --mode development" },
這樣,當執行npm start的時候,就會使用webpack-dev-server把index.js相關文件打包,生成bundle.js,這時候瀏覽器會打開一個窗口,執行index.html(contentBase裏面定義了),又由於index.html裏面引入了bundle.js,就能夠把壓縮後的js文件執行起來。固然引入bundle.js這一步能夠由咱們強大的html-webpack-plugin完成。web
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
在根目錄下新建.babelrc文件,而後添加npm
{ "presets": [ "@babel/preset-env", "@babel/preset-react" ] }
在webpack.config.js裏面添加babel-loader配置json
module.exports = { ... module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'] } ] }, resolve: { extensions: ['*', '.js', '.jsx'] } ... };
npm install --save react react-dom
修改index.js: 這個ReactDOM.render就是把元素渲染到index.html裏面id爲'app'的元素廈門。在實際開發中,咱們會把app.js渲染到這裏,而後在app.js裏面寫redux,react-router構成的頁面的起點。redux
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.jsbabel
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();
這個時候執行npm start,就能夠在瀏覽器訪問http://localhost:8080看到Index.html裏面的內容啦啦。參考連接:
https://www.robinwieruch.de/m...