/webpack-react-zero

webpack4从零开始搭建简单的React16开发环境

Primary LanguageJavaScript

webpack4从零开始搭建简单的React16开发环境

  1. 初始化项目 npm init -y

  2. 安装webpackwebpack-dev-server npm i webpack webpack-cli webpack-dev-server -D

  3. 安装reactreact-dom npm i react react-dom -S

  4. 因为react中使用JSX语法, 需要安装babel来编译它 npm install babel-loader @babel/core @babel/preset-env @babel/preset-react -D

  5. 在根目录下新建babel配置文件.babelrc

    {
        "presets": [
            "env",
            "react"
        ]
    }
  6. 新建public目录,然后创建index.html文件,在body标签中增加<div id="root"></div>

  7. 新建src目录然后在里面新建index.js文件

    import React from 'react';
    import ReactDOM from 'react-dom';
    
    ReactDOM.render(
        <h1>Hello World</h1>,
        document.getElementById('root')
    )
  8. 安装html-webpack-plugin,用于打包时将html文件复制到目标文件夹 npm i html-webpack-plugin -D

  9. 安装clean-webpack-plugin插件,用于在打包前清空目标文件夹 npm i clean-webpack-plugin -D

  10. 编写webpack.config.js

const path = require('path');
// 插件都是一个类,所以我们命名的时候尽量用大写开头
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
  // 入口文件
  entry: {
    app: './src/index.js'
  },
  // 输出到dist文件夹, 文件名字为bundle.js
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, './dist')
  },
  // 配置开发服务器使用的端口及目录
  devServer: {
    port: 3000,
    contentBase: './dist'
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: 'babel-loader', //使用babel转换jsx语法
        exclude: /node_modules/
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(), //打包前先清空目标文件夹中所有文件
    new HtmlWebpackPlugin({
      template: './public/index.html', // 用src/index.html作为模板
      hash: true, // 会在打包好的bundle.js后面加上hash串
    })
  ]
}
  1. 编辑package.json文件, 在scripts里面加入"dev""build"

      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "dev": "webpack-dev-server --open",
        "build": "webpack --mode production"
      }
  2. 在终端执行npm run build进行打包,执行npm run dev运行开发测试

参考: webpack4从零配置搭建简单的React16开发环境 webpack4 搭建react babel7遇到坑