1、安装配置babel
yarn add babel-loader @babel/core @babel/preset-env
2、webpack.config.js配置module
module: { rules: [ { test: /.js$/, exclude: /node_modules/, loader: "babel-loader" } ] },
3、安装react及react、react-dom
yarn add react react-dom @babel/preset-react
4、项目根目录下新建.babelrc,里面内容如下
{ "presets": ["@babel/preset-env","@babel/preset-react"] }
5、在webpack配置的入口文件中写如下代码
import React,{Component} from 'react' import ReactDom from 'react-dom' class App extends Component{ render(){ return <div>我是react应用</div> } } ReactDom.render(<App/>,document.querySelector('#root'))
6、webpack要引入HtmlWebpackPlugin,并配置有<div id=root></div>的html文件为模板文件
yarn add html-webpack-plugin
src/public/index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="root"></div> </body> </html>
webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { entry: { main: './src/main.js' }, module: { rules: [ { test: /.js$/, exclude: /node_modules/, loader: "babel-loader" } ] }, plugins: [ new HtmlWebpackPlugin({ template: './src/public/index.html' }) ], output: { path: path.resolve(__dirname,'dist'), filename: '[name].js' } }
7、webpack-dev-server打开,页面出现我是react应用则打包成功。