一个react工程的建立

1、create-react-app


# 安装 create-react-app 命令,如果已将安装请忽略
npm install -g create-react-app
# 创建 react项目
create-react-app react-electron

目录结构调整

.
|——config
|   |——webpack.dev.js
|   |——webpack.pro.js
|——src
|   |——layouts
|   |——pages
|   |——service
|   |——util
|   |——index.js
|   |——route.js
|——public
|   |——index.html
|   |——favicon.ico
|——dist

2、webpack

npm install webpack webpack-cli webpack-bundle-analyzer extract-text-webpack-plugin  --save-dev
npm install --save-dev extract-text-webpack-plugin@next

–save-dev 是你开发时候依赖的东西,–save 是你发布之后还依赖的东西。==

3、babel

npm install --save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react babel-preset-stage-0

版本依赖:

"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",

新建babel配置文件.babelrc

 {
  "presets": [
    ["es2015", {"modules": false}], "react", "stage-0"],
    "plugins": [
      // ["import", { "libraryName": "antd", "style": true   /* or 'css' */}],
      ["react-hot-loader/babel"]
      // ["transform-decorators-legacy"]
      // ,["transform-runtime"]
    ]
  // ,"env": {
  //   "development": {
  //     "presets": ["react-hmre"]
  //   }
  // }
}

4、加载 CSS和 less

npm install --save-dev style-loader css-loader
npm install --save-dev less-loader less

5、 加载图片

npm install --save-dev url-loader file-loader

6、增加HtmlWebpackPlugin

HtmlWebpackPlugin作用是生成一个HTML模板。
HtmlWebpackPlugin简化了HTML文件的创建,以便为你的webpack包提供服务。这对于在文件名中包含每次会随着编译而发生变化哈希的 webpack bundle 尤其有用。

你可以让插件为你生成一个HTML文件,使用lodash模板提供你自己的模板,或使用你自己的loader

npm install --save-dev html-webpack-plugin

7、模块热替换

允许在运行时更新各种模块,而无需进行完全刷新。
有两种方式:

一、更改package.json

"dev": "webpack --config build/webpack.dev.config.js --color --progress --hot"

然后更改index.js

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

**if (module.hot) {
    module.hot.accept();
}**
//增加

二、 更改webpack配置文件

const webpack = require('webpack');

devServer: {
    hot: true
}

plugins:[
     new webpack.HotModuleReplacementPlugin()
]

8、安装必要包

1 router 和 redux

npm install --save react-router react-router-dom react-redux  redux redux-thunk 

2 react-hot-loader:

能让修改的部分自动刷新。但这和自动刷新网页是不同的,因为 hot-loader 并不会刷新网页,而仅仅是替换你修改的部分,也就是上面所说的 without losing state。
hot-loader 是基于 webpack-dev-server,所以还得安装 webpack-dev-server

npm install --save-dev react-hot-loader webpack-dev-server

3 cross-env

运行跨平台设置和使用环境变量的脚本,使用NODE_ENV =production, 来设置环境变量

npm install --save-dev cross-env

9、webpack配置

开发环境:

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const DIST_PATH = path.resolve(__dirname, '../dist'); //生产目录
const APP_PATH = path.resolve(__dirname, '../src'); //源文件目录

module.exports = {
    entry: {
        index:['react-hot-loader/patch'
        ,'webpack-dev-server/client?http://localhost:8080'
        ,'webpack/hot/only-dev-server'
        ,path.resolve(APP_PATH, 'index.js')]
    },
    output: {
        path: DIST_PATH, //出口路径
        filename: '[name].js',
        // chunkFilename: 'js/[name].[chunkhash].js', //按需加载名称
        publicPath: "/"
    },
    // target: 'electron-renderer',
    devtool: 'eval-source-map',
    module: {
        rules: [
            { test: /\.jsx?$/, use: ['babel-loader'], include: APP_PATH },
            { test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader'] },
            { test: /\.css$/, use: ['style-loader', 'css-loader'] },
            { test: /\.(png|svg|jpg|gif)$/, use: ['url-loader'] }
        ]
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NamedModulesPlugin(),
        new HtmlWebpackPlugin({
            template: 'public/index.html'
        })
        // new webpack.DllReferencePlugin({
        //     context: __dirname,
        //     manifest: require("./build/bundle.manifest.json"),
        // }),
    ],
    devServer: {
        historyApiFallback: true,
        hot: true,
        inline: true,
        // port: 8081,
        proxy: {
            // "/xxxx":{
              // target: "http://ip:port",
            // }
        }
    },
}

package.json:

"dev": "webpack-dev-server --progress --watch --color --config config/webpack.dev.js"

生产环境

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');

const DIST_PATH = path.resolve(__dirname, '../dist'); //生产目录
const APP_PATH = path.resolve(__dirname, '../src'); //源文件目录

var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
var ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
    entry: {
        index: [path.resolve(APP_PATH, 'index.js')]
    },
    output: {
        path: DIST_PATH, //出口路径
        // filename: '[name].js',
        filename: '[name].[chunkhash:6].js',
        publicPath: "./"
    },
    // target: 'electron-renderer',
    // devtool: 'eval-source-map',

    module: {
        rules: [
            { test: /\.jsx?$/, use: ['babel-loader'], include: APP_PATH },
            {
                test: /\.less$/,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: ['css-loader', 'less-loader']
                })
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: ['css-loader']
                })
            },
            { test: /\.(png|svg|jpg|gif)$/, use: ['url-loader'] }
        ]
    },
    optimization: {
        splitChunks: {
            chunks: "initial", // 必须三选一: "initial" | "all"(默认就是all) | "async"
            minSize: 0, // 最小尺寸,默认0
            minChunks: 1, // 最小 chunk ,默认1
            name: 'vendor',
            minChunks: 1
        },
        nodeEnv: 'production',
        minimizer: [
            new TerserPlugin({
                cache: true, // 开启缓存
                parallel: true, // 支持多进程
                sourceMap: true, 
            }),
        ]
    },
    plugins: [
       
        new BundleAnalyzerPlugin(),

        new HtmlWebpackPlugin({
            template: 'public/index.html'
        }),
        new ExtractTextPlugin({
            filename: '[name].[chunkhash:6].css',
            allChunks: true
        }),

    ]

}

package.json:

"build": "webpack --mode production --progress --profile --hide-modules --config config/webpack.pro.js",

参考链接:

  • https://segmentfault.com/a/1190000018081262?utm_source=tag-newest
  • https://segmentfault.com/a/1190000014466696

更多

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值