# webpack-build-react **Repository Path**: AlanLee97/webpack-build-react ## Basic Information - **Project Name**: webpack-build-react - **Description**: webpack手动构建react - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-10-31 - **Last Updated**: 2021-10-31 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 初始化项目 ```bash mkdir webpack-bulid-react cd webpack-build-react npm init -y ``` # 安装webpack和react及相关依赖 1. 安装webpack ```bash npm i webpack webpack-cli webpack-dev-server -D ``` 2. 安装react ```bash npm i react react-dom -S ``` 3. 安装react相关babel依赖 ```bash npm i @babel/core @babel/preset-react @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators @babel/plugin-transform-runtime @babel/preset-env -D ``` - @babel/core:babel 核心包,编译器,提供转换的API。 - @babel/preset-react:Babel可以转换JSX语法 - @babel/plugin-proposal-class-properties:解析类的属性 - @babel/plugin-proposal-decorators:解析装饰器 - @babel/plugin-transform-runtime:将 helper 和 polyfill 都改为从一个统一的地方引入,并且引入的对象和全局变量是完全隔离的,可以提高代码重用性,缩小编译后的代码体积 - @babel/preset-env:对es2015, es2016. es2017的支持 ​ 4. 安装webpack插件和loader ```bash npm i html-webpack-plugin clean-webpack-plugin babel-loader style-loader css-loader -D ``` 5. 配置webpack webpack.config.js ```javascript const path = require('path'); const HtmlWebapckPlugin = require('html-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); module.exports = { entry: "./src/index.js", output: { filename: "bundle.js", path: path.resolve(__dirname, "dist") }, module: { rules: [ { test: /\.(ts|tsx|js|jsx)?$/, use: ["babel-loader"] }, { test: /\.(css|scss)?$/, use: ["style-loader", "css-loader"] } ] }, plugins: [ new CleanWebpackPlugin(), new HtmlWebapckPlugin({ template: "./public/index.html" }) ], devServer: { hot: true, port: 3000, open: true, }, mode: "development" } ``` 创建.babelrc文件 ```json { "presets": ["@babel/preset-react", "@babel/preset-env"], "plugins": [ [ "@babel/plugin-proposal-class-properties", //编译类 { "loose": true //将编译类属性以使用赋值表达式而不是Object.defineProperty } ], ["@babel/plugin-transform-runtime"] ] } ``` 6. 目录结构 ![image.png](https://gitee.com/AlanLee97/public-asset/raw/master/note_images/1635610826197-d66e530f-a8e0-4c24-96bb-165d157931ad.png) 创建public/index.html、src/index.js、src/App.jsx文件 public/index.html ```html Webpack Build React
``` src/index.js ```javascript import React from "react"; import ReactDom from "react-dom"; import App from "./App.jsx"; ReactDom.render( , document.getElementById("root") ) ``` src/App.jsx ```javascript import React from "react"; class App extends React.Component { constructor() { super(); } render() { return

Hello, Webpack + React

} } export default App; ``` # 运行 ```bash npm run serve ``` ![image.png](https://gitee.com/AlanLee97/public-asset/raw/master/note_images/1635610733146-b51a57a9-dbe7-4801-9c48-2c97be6f8698.png)