基于webpack的React项目搭建(三)

前言

  搭建好前文的开发环境,已经可以进行开发。然而实际的项目中,不同环境有着不同的构建需求。这里就将开发环境和生产环境的配置单独提取出来,并做一些简单的优化。

  • 分离不同环境公有配置

  不同环境虽然有不同的构建需求,但依然有相同的部分,这里将共同部分提取出来,单独配置,其他环境再合并共有配置即可。安装webpack-merge(用于合并配置)、uglifyjs-webpack-plugin(js代码压缩,这里单独提取出来控制版本)和rimraf(跨平台删除工具)。

1
npm install webpack-merge uglifyjs-webpack-plugin rimraf --save-dev

  接下来配置共有配置webpack.config.js。

复制代码
const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: ['babel-polyfill', path.resolve(__dirname, '../src/index.js')],// 指定入口文件,程序从这里开始编译,__dirname当前目录, ../表示上一级目录, ./同级目录
  output: {
    path: path.resolve(__dirname, '../dist'), // 输出的路径
    filename: 'app/[name]_[hash:8].js', // 打包后文件
  },
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.(js|jsx)$/,
        loader: 'eslint-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.(js|jsx)$/,
        loader: 'babel-loader', // 加载器
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        use: [
          {
            loader: 'style-loader',
          },
          {
            loader: 'css-loader',
          },
        ],
      },
      {
        test: /\.less$/,
        use: [{
          loader: 'style-loader',
        }, {
          loader: 'css-loader',
        }, {
          loader: 'less-loader',
          options: {
            sourceMap: true,
          },
        }],
      },
    ],
  },
};
复制代码

   配置开发环境webpack.dev.config.js。

复制代码
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const merge = require('webpack-merge');
const webpackConfig = require('./webpack.config');

process.env.NODE_ENV = 'development';

module.exports = merge(webpackConfig, {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'babel-polyfill',
    'react-hot-loader/patch',
    'webpack-dev-server/client?http://localhost:9090',
    'webpack/hot/only-dev-server',
    path.resolve(__dirname, '../src/index.js'),
  ],
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '../src/index.template.html'),
      inject: true,
    }),
    new webpack.NoEmitOnErrorsPlugin(),
  ],
});
复制代码

  由于生产环境不需要热更新等,所以入口文件和以前的index.js有所不同。这里在src目录下新建index.prod.js,编辑如下。

复制代码
/*eslint-disable*/
import React from 'react';
import { render } from 'react-dom';
import 'babel-polyfill'; import App from
'./App'; const renderDom = Component => { render( <Component />, document.getElementById('app') ); }; renderDom(App);
复制代码

  配置生产环境webpack.prod.config.js。

复制代码
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const merge = require('webpack-merge');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const webpackConfig = require('./webpack.config');

process.env.NODE_ENV = 'production';

module.exports = merge(webpackConfig, {
entry: [
'babel-polyfill',
path.resolve(__dirname, '../src/index.prod.js'),
],
plugins: [
new UglifyJSPlugin({
uglifyOptions: {
output: {
comments: false,
beautify: false,
},
},
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production'),
}),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, '../src/index.template.html'),
inject: true,
minify: {
html5: true,
collapseWhitespace: true,
removeComments: true,
removeTagWhitespace: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
},
}),
],
});
复制代码

  配置package.json,新建三个执行脚本。

"scripts": {
    "dev": "node bin/dev-server",
    "build": "npm run clean && webpack --config webpack/webpack.prod.config.js",
    "devbuild": "npm run clean && webpack --config webpack/webpack.dev.config.js",
    "clean": "rimraf dist"
  }
# 启动开发调试
npm run dev
# 开发环境构建
npm run devbuild
# 生产环境构建
npm run build
  • 打包简单优化

  我们在构建的时候,往往希望自己的代码和第三方库分离开来,修改webpack.config.js。

复制代码
......
entry: { app: [
'babel-polyfill', path.resolve(__dirname, '../src/index.js')], vendor: ['react', 'react-dom', 'babel-polyfill'], }, resolve: { // 指定第三方库目录,减少webpack寻找时间 modules: [path.resolve(__dirname, '../node_modules')], },
......
plugins: [
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: Infinity, }), ],
......
复制代码
posted @   Raion  阅读(2789)  评论(2编辑  收藏  举报
编辑推荐:
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
阅读排行:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!
· 用 C# 插值字符串处理器写一个 sscanf
点击右上角即可分享
微信分享提示