关于react.js:webpack从零搭建react应用

24次阅读

共计 3191 个字符,预计需要花费 8 分钟才能阅读完成。

在上一篇文章中咱们用 webpackwebpack-cli搭建了最简略的前端利用,通常在我的项目中咱们会用 vue 或者react, 咱们看下如何利用咱们本人搭的工程来适配react

注释开始 …

前置

首先咱们要确定,react并不是在 webpack 中像插件一样装置就能够间接应用,咱们须要反对 jsx 以及一些 es6 的一些比拟新的语法,在 creat-react-app 这个脚手架中曾经帮咱们高度封装了 react 我的项目的一些配置,甚至你是看不到很多的配置,比方 @babel/preset-react 转换 jsx 等。所以咱们须要晓得一个 react 我的项目须要哪些插件的前提条件, 本文次要参考从头开始打造工具链

装置 babel 相干插件

npm i @babel/core @babel/cli @babel/preset-env @babel/preset-react --save

其中 babel/core 就是能将代码进行转换,@babel/cli容许命令行编译文件,babel/preset-env与 @babel/preset-react 都是预设环境,把一些高级语法转换成es5

装置好相干插件后,咱们须要在根目录中创立一个 .babelrc 来让 babel 告诉那两个预设的两个插件失效

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

接下来咱们须要装置在 react 中的反对的 jsx,次要依赖babel-loader 来编译jsx

npm i babel-loader --save-dev

并且咱们须要改下 webpack.config.jsloader

{
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      },
      {test: /\.(png|svg|jpg|gif|jpeg)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              outputPath: 'assets',
              name: '[name].[ext]?[hash]'
            }
          }
        ]
      },
      {test: /\.(js|jsx)$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        options: {presets: ['@babel/env']
        }
      }
    ]
  },
}

react 中咱们设置 HMR,咱们须要联合new webpack.HotModuleReplacementPlugin(), 并且在devServer 中设置 hottrue

module.exports = {
 ...
 plugins: [
    new HtmlWebpackPlugin({template: './public/index.html'}),
    new miniCssExtractPlugin({filename: 'css/[name].css'
    }),
    new webpack.HotModuleReplacementPlugin()],
  devServer: {hot: true}
}

残缺的配置 webpack.config.js 就曾经 ok 了

// webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const miniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
  mode: 'development',
  entry: {app: './src/app.js'},
  output: {path: path.resolve(__dirname, 'dist'),
    filename: '[name].bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      },
      {test: /\.(png|svg|jpg|gif|jpeg)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              outputPath: 'assets',
              name: '[name].[ext]?[hash]'
            }
          }
        ]
      },
      {test: /\.(js|jsx)$/,
        loader: 'babel-loader',
        options: {presets: ['@babel/env']
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({template: './public/index.html'}),
    new miniCssExtractPlugin({filename: 'css/[name].css'
    }),
    new webpack.HotModuleReplacementPlugin()],
  devServer: {hot: true}
};

装置 reactreact-dom 这两个外围库

npm i react react-dom --save-dev

src 目录下新建一个App.jsx

// App.jsx
import React, {Component} from 'react';
import deepMerge from './utils/index.js';
import '../src/assets/css/app.css';
import image1 from '../src/assets/images/1.png';
import image2 from '../src/assets/images/2.jpg';

class App extends Component {constructor(props) {super(props)
    this.state = {
      text: 'hello webpack for react',
      name: "Maic",
      age: 18,
      publicName: 'Web 技术学苑',
      imgSource: [image1, image2]
    }
  }
  render() {const { text, name, age, publicName, imgSource} = this.state;
    return (<>
      <div className="app">
          <h1>{text}</h1>
          <div>
            <p>{name}</p>,<span>{age}</span> 岁
            <p>{publicName}</p>
          </div>
          <div>
            {imgSource.map(src => <img src={src} key={src} />)
            }
          </div>
      </div>
    </>)
  }
}
export default App

咱们在 app.js 中引入App.jsx

// app.js
import React from 'react';
import {createRoot} from 'react-dom/client';
import App from './App.jsx';
const appDom = document.getElementById('app');
const root = createRoot(appDom);
root.render(<App />);

咱们运行 npm run server, 浏览器关上localhost:8080

ok,用webpack 搭建的一个本人的 react 利用就曾经 ok 了

总结

1、react 须要的一些插件,@babel/core@babel/cli@babel/preset-env@babel/preset-reactbabel-loader

2、设置.babelrc

3、引入 reactreact-dom,modules 中设置 babel-loader 编译 jsx 文件

4、本文 code-example

正文完
 0