// index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> // react需要的渲染根元素 <div></div> </body> </html>
此时webpack.config.js配置:
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { filename: 'https://www.jb51.net/article/app.js', path: path.resolve(__dirname, 'dist') }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader' } }, { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.(png|svg|jpg|gif)$/, use: ['url-loader'] }, { test: /\.(woff|woff2|eot|ttf|otf)$/, use: ['url-loader'] } ] }, plugins: [ new HtmlWebpackPlugin({ title: 'production', template: './index.html' // 模板文件位置 }) ] };
书写React,运行webpack
// src/index.js import React from 'react'; import ReactDom from 'react-dom'; import './main.css' ReactDom.render( <h1>hello world</h1>, document.getElementById('root') );
运行npm run build,生成dist目录,打开dist目录中的index.html文件,可以发现浏览器已正常渲染"hello world"。
dev环境热更新配置
react的wepack完成以后,是不是发现每修改一次代码,想看到效果,得重新打包一次才行。webpack-dev-server配置可以帮助我们实现热更新,在开发环境解放我们的生产力。
安装webpack-dev-server
npm install webpack-dev-server --save-dev
webpack.config.js 配置
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const webpack = require('webpack'); module.exports = { entry: './src/index.js', output: { filename: 'https://www.jb51.net/article/app.js', path: path.resolve(__dirname, 'dist') }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader' } }, { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.(png|svg|jpg|gif)$/, use: ['url-loader'] }, { test: /\.(woff|woff2|eot|ttf|otf)$/, use: ['url-loader'] } ] }, plugins: [ new HtmlWebpackPlugin({ title: 'production', template: './index.html' }), // hot 检测文件改动替换plugin new webpack.NamedModulesPlugin(), new webpack.HotModuleReplacementPlugin() ], // webpack-dev-server 配置 devServer: { contentBase: './dist', hot: true }, };
运行webpack-dev-server
在 package.json 文件 加入 scripts 配置:
"scripts": { "build": "webpack", "dev": "webpack-dev-server --open --mode development" // webpack-dev-server },
命令行运行 npm run dev
可以在浏览器中输入localhost:8080 内容即为dist目录下的index.html内容。修改src/index.js中的内容或者依赖,即实时在浏览器热更新看到。
至此,react的webpack的基础开发环境已全部配置完毕。