1.初始化项目
npm init
填写基本信息,生成package.json
2.安装依赖包
webpack、babel、react等,webpack、babel工具类使用npm install --save-dev 安装在“devDependencies”下。
{
"name": "webpack+react",
"version": "1.0.0",
"main": "src/index.html",
"author": "yq",
"license": "ISC",
"description": "666",
"repository": {
"type": "git",
"url": ""
},
"scripts": {
"dev": "",
"start": "webpack-dev-server --config ./build/webpack.config.js",
"build": "webpack --config ./build/webpack.config.js"
},
"dependencies": {
"antd": "^4.18.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.6",
"react-router": "^6.2.1",
"redux": "^4.1.2"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^5.5.0",
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.7.1"
}
}
注:
1.webpack-dev-server 指定目录下的js启动项目
2.webpack 进行项目代码打包
3.babel 代码转化为es5,提升兼容性
3.新建项目目录结构
.babelrc文件配置【该文件在项目根目录】
{
"presets": ["react", "es2015"],
"env": {
"dev": {
"plugins": [["react-transform", {
"transforms": [{
"transform": "react-transform-hmr",
"imports": ["react"],
"locals": ["module"]
}]
}]]
}
}
}
4.配置webpack.config.js
const path = require('path');
const webpack = require("webpack");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: "development",//当前环境为开发环境
entry: './src/index.jsx', //js入口文件;
output: {
path: path.resolve(__dirname, '../dist'), //利用path包获取绝对文件路径
filename: 'bundle.js' //打包成功后的文件名<br>
}, //js出口文件;路径加文件名;
module: {
rules: [//添加项目规则loader插件
{
test: /\.(jsx)$/,//转译jsx语法为js
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
plugins: [//插件实例化
new HtmlWebpackPlugin({
template: "src/index.html",
inject: "body",
filename: "index.html",
}) //在 body 中使用 script 标签引入你所有 webpack 生成的 bundle。
],
devServer: {
static: path.resolve(__dirname, '../src'), //启动入口
port: 9000,
hot: true,
proxy: {//代理服务器 api请求跨域
'/api': {
target: 'http://server.com',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
以上配置完成后在src/index.html页面中会显示引入的bundle.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" charset="utf-8">
<title></title>
</head>
<body>
<div id="root"></div>
<!-- <script src="./bundle.js"></script> -->
</body>
</html>