快速启动一个Webpack + React项目

本文适用于对 react / webpack 有一定使用经验的开发人员。

快速启动一个React项目,现在有很多工具,比如create-react-app、Dva、Umi等等,可以参考这个网站
脚手架市场 提供了各种方案,但有时候,你可能需要更灵活的配置,又不用去熟悉脚手架的api,或者只是起个练手的小项目,不想要太多附加功能,只需要一些必须的依赖,可以参考下下面的配置:
主要是两个文件,一个是package.json,安装需要的依赖包,一个是webpack.config.js的开发环境配置。

主要文件目录:

├── node_modules                        # 包库,自动生成
├── dist                                # 打包生成的文件
├── src                                 # 主程序目录
│   ├── app.js                          # component
│   ├── index.js                        # 入口文件
│   ├── index.less                      # css文件
├── .babelrc                            # babel 配置文件           
├── .eslintrc.json                      # eslint规则文件              
├── .gitignore                          
├── postcss.config.js                   # postcss 配置文件,如果使用了postcss添加,否则不需要  
├── package.json  
├── webpack.config.js                   # 通过webpack启动服务以及打包
├ -- - server.js (可选)               # 通过node启动服务 ,和webpack.config.js二选一即可
├── README.md    
                    

代码参考:simpleReact
package.json

{
  "name": "app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "clean": "rm dist/bundle.js",
    "server": "node server.js",
    "start": "webpack-dev-server --open",
    "watch": "webpack --watch",
    "build-dev": "webpack -d --mode development",
    "build-prod": "webpack -p --mode production",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "iris",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.6.4",
    "@babel/preset-env": "^7.6.3",
    "@babel/preset-react": "^7.6.3",
    "autoprefixer": "^9.7.1",
    "babel-loader": "^8.0.6",
    "clean-webpack-plugin": "^3.0.0",
    "css-loader": "^3.2.0",
    "eslint": "^6.6.0",
    "file-loader": "^4.2.0",
    "html-webpack-plugin": "^3.2.0",
    "html-webpack-template": "^6.2.0",
    "isomorphic-fetch": "^2.2.1",
    "less": "^3.10.3",
    "less-loader": "^5.0.0",
    "lodash-webpack-plugin": "^0.11.5",
    "node-sass": "^4.13.0",
    "postcss-loader": "^3.0.0",
    "sass-loader": "^8.0.0",
    "style-loader": "^1.0.0",
    "url-loader": "^2.2.0",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.9.0"
  },
  "dependencies": {
    "react": "^16.11.0",
    "react-dom": "^16.11.0",
    "moment": "^2.24.0",
    "lodash": "^4.17.15"
  }
}

webpack.config.js

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');

const config = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash].js'
  },
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.css/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1
            }
          },
          'postcss-loader'
        ]
      },
      {
        test: /\.scss$/,
        use: [
          'style-loader',
          'css-loader',
          'sass-loader'
        ]
      },
      {
        test: /\.less$/,
        use: [
          'style-loader',
          'css-loader',
          'less-loader'
        ]
      },
      {
        test: /\.svg$/,
        use: 'file-loader'
      }, 
      {
        test: /\.png/,
        use: [
          {
            loader: 'url-loader',
            options: {
              mimetype: 'image/png'
            }
          }
        ]
      }
    ]
  },
  resolve: {
    extensions: [
      '.js',
      '.jsx'
    ]
  },
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './dist',
    // port: 9000, 使用npm run start启动时,开启
  },
  plugins: [
    new CleanWebpackPlugin(),
    new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
    new LodashModuleReplacementPlugin,
    new HtmlWebpackPlugin({
      template: require('html-webpack-template'),
      inject: false,
      appMountId: 'app'
    })
  ],
  optimization: {
    runtimeChunk: 'single',
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          // chunks: 'all'
        }
      }
    }
  }
};

module.exports = config;

安装的依赖包简介

1.开发库依赖


React框架

react
react-dom

工具库

moment: moment
lodash: lodash

2.开发环境依赖


构建服务

webapck
webapck-dev-server webpack-cli

编译

Babel: babel-loader @babel/core @babel/preset-react @babel/preset-env
* 注意babel-loader的版本,7以上需要使用@开头的插件。
配置文件:.babelrc

{
    presets: [
    [
        '@babel/preset-env',
        {
            modules: false
        }
    ],
    '@babel/preset-react'
    ]
}

CSS

css: css-loader style-loader
PostCss: postcss-loader autoprefixer
Less: less-loader less
Sass: sass-loader node-sass
*css必备,其他按需选择,推荐PostCss
PostCss配置文件:postcss.config.js

module.exports = {
    plugins: [
        require('autoprefixer')
    ]
}

图片解析

SVG: file-loader
PNG: url-loader

代码检查

ESlint: eslint
配置文件:.eslintrc.json

webpack优化

html-webpack-plugin 生成html
html-webpack-template 生成html模板
lodash(dev): lodash-webpack-plugin
clean-webpack-plugin 打包前清除文件

接口

接口请求可以参考配置webpack的 devServerProxy 的配置,推荐使用 isomorphic-fetch发起接口请求。

项目启动

编辑好需要的文件,主要是src, package.json, webpack.config.js, 及一些配置文件,
然后执行npm install
启动项目:npm start

git配置参考

git init 初始化
git commit -m "first commit" 提交
git remote add origin [email protected]:xxx/simpleReact.git 添加远程库地址
git push -u origin master 推送到远程

你可能感兴趣的:(快速启动一个Webpack + React项目)