项目结构
需要用的 库
react
, react-dom
, webpack
, webpack-cli
, webpack-dev-server
插件和 loader:
@babel/core
, @babel/preset-env
,@babel/preset-react
,babel-loader
, html-webpack-plugin
基础配置
webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'development',
devtool: 'none',
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve('dist')
},
devServer: {
port: 3000,
hot: true
},
module: {
rules: [
{
test: /\.js|jsx$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react']
}
}
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
]
}
package.json
{
"name": "reactProject",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.13.8",
"@babel/preset-env": "^7.13.9",
"@babel/preset-react": "^7.12.13",
"babel-loader": "^8.2.2",
"html-webpack-plugin": "^4.5.2",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"webpack": "^4.46.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.2"
}
}
// src/index.js
import React from 'react'
import { render } from 'react-dom'
// 自定义组件
function App() {
return <div>React</div>
}
render(<App />, document.getElementById('root'))
安装 执行
npm install
运行 devServer
npx webpack-dev-server