自己构建React项目

如果没有create-react-app,我们应该如何构建项目呢?今天让我们一起通过自己的方式打包react项目吧!

第一步创建文件

mkdir react-boiler-plate
cd react-boiler-plate

然后初始化npm

npm init -y

然后准备一个这样的目录结构

build
public
src
package.json

开始安装依赖了

npm i react react-dom
npm i webpack webpack-cli webpack-dev-server html-webpack-plugin -D
npm i @babel/core @babel/preset-react @babel/preset-env babel-loader style-loader css-loader -D

创建一个webpack.config.js的配置文件

const path = require('path')
const HTMLplugin = require('html-webpack-plugin')

module.exports = {
  entry: path.join(__dirname, 'src', 'index.js'),
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, './build')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },
  plugins: [
    new HTMLplugin({
      template: './public/index.html'
    })
  ]
}

在public里面建模板文件index.html


<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Documenttitle>
head>
<body>
  <div id="root">div>
body>
html>

在src里面建入口文件index.js

import React from 'react';
import ReactDOM from 'react-dom';

const App = () => {
  return <h1>hello world</h1>
}

ReactDOM.render(<App />, document.getElementById('root'))

创建babel的配置文件.babelrc

{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

在package.json里面添加几个运行的脚本

  "scripts": {
    "start": "webpack-dev-server --mode development --open --hot",
    "build": "webpack --mode production"
  }

到此为止项目已经配置完成,运行npm run start即可浏览

你可能感兴趣的:(自己构建React项目)