虽然已经有了create-react-app这种非常方便的工具,但是封装了太多,对于里面的一些细节不是很了解,所以很有必要手动创建。

创建项目目录

mkdir react-projectcd react-project

初始化package.json

yarn init

在填写回答的时候,entry point写app/main.js,其他问题全部回车即可

~ yarn inityarn init v1.12.3question name (react-project):question version (1.0.0):question description:question entry point (index.js): app/main.jsquestion repository url:question author:question license (MIT):question private:success Saved package.json✨  Done in 16.91s.

安装依赖

yarn add --dev webpack webpack-cli @babel/core @babel/preset-env @babel/preset-react html-webpack-plugin webpack-merge babel-loaderyarn add react react-dom prop-types

创建目录结构

/---babel.config.js+---app|   \---main.js|   \---index.html+---build|   \---webpack.config.base.js|   \---webpack.config.dev.js|   \---webpack.config.prod.jd

babel.config.js

module.exports = {  "presets": [    [      "@babel/preset-env",      {        "useBuiltIns": "entry",        "targets": {          "browsers": [            "cover 99.5% in CN"          ]        }      }    ],    "@babel/preset-react"  ]}

app/main.js

import ReactDOM from "react-dom";import React from "react";function App() {    return (        <div className="App">            <h1>Hello World</h1>        </div>    );}const rootElement = document.getElementById("root");ReactDOM.render(<App/>, rootElement);

app/index.html

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>    <title><%= htmlWebpackPlugin.options.title %></title></head><body><div id="root"></div></body></html>

build/webpack.config.base.js

"use strict";var path = require("path");var HtmlWebpackPlugin = require("html-webpack-plugin");module.exports = {    entry: path.resolve(__dirname, "../app/main.js"),    output: {        path: path.resolve(__dirname, "../dist"),        filename: "bundle.js"    },    module: {        rules: [            {                test: /\.js$/,                exclude: /(node_modules|bower_components)/,                use: {                    loader: "babel-loader"                }            }        ]    },    plugins: [        new HtmlWebpackPlugin({            template: "app/index.html"        })    ]};

build/webpack.config.dev.js

"use strict";var baseWebpackConfig = require("./webpack.config.base");var merge = require("webpack-merge");module.exports = merge(baseWebpackConfig, {    mode: "development",    devtool: "source-map"});

build/webpack.config.prod.js

"use strict";var baseWebpackConfig = require("./webpack.config.base");var merge = require("webpack-merge");var path = require("path");module.exports = merge(baseWebpackConfig, {    mode: "production",    output: {        path: path.resolve(__dirname, "../dist"),        filename: "bundle.[hash].js"    }});

package.json里加scripts

  "scripts": {    "build:dev": "webpack --config build/webpack.config.dev.js",    "build:prod": "webpack --config build/webpack.config.prod.js"  }

编译代码

做完上面的所有步骤就可以执行编译命令了,yarn build:dev或者yarn build:prod