从零开始React项目架构(四)

1,224 阅读2分钟

前言


使用当前的webpack配置能不能打包构建项目呢?当然可以,但这不是我们想要的,所以,让我们来看一看生产环境需要怎么配置webpack吧

开发


  1. 生产环境配置
    在根目录创建webpack.pro.config.js
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

module.exports = {
    entry:{
        main:['babel-polyfill','./src/index.js'],        
        vendors: ['react','react-dom','react-router-dom','whatwg-fetch']
    }
    ,
    output:{
        path:path.resolve(__dirname,'dist'),
        filename:'bundle.[hash:4].js'
    },
    module:{
        rules:[
            {  
                test: /\.(woff|eot|ttf|svg|png|jpg)$/,  
                use: [  
                    {  
                        loader: 'url-loader',  
                        options: {  
                            limit: '1024' ,
                            name: '[name].[hash:4].[ext]'  
                        }                        
                    },  
                ]  
            },
            {  
                test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
                use: [  
                    {  
                        loader: 'url-loader',  
                        options: {  
                            limit: '1024',
                            name: '[name].[hash:4].[ext]'  
                        }  
                    },  
                ]  
            },
            {
                test: /\.(css|less)$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: ["css-loader","less-loader"]
                })
            },
            {
                test:/\.(js|jsx)$/,
                use:"babel-loader",
                exclude:/node_modules/
            }
        ]
    },
    devtool: false,
    plugins:[
        // html 模板插件
        new HtmlWebpackPlugin({template:'./src/index.html',favicon: './public/favicon.png'}),
        // 启用作用域提升,让代码文件更小、运行的更快
        new webpack.optimize.ModuleConcatenationPlugin(),
        // 提取公共代码vendors
        new webpack.optimize.CommonsChunkPlugin({
            name:'vendors',
            filename:'[name].[hash:4].js'
        }),
        // 抽离出css
        new ExtractTextPlugin("style.css"),
        // 压缩js代码
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false,
                drop_console: true,
                pure_funcs: ['console.log']
            }
        }),
        // 定义全局常量
        new webpack.DefinePlugin({
            "process.env": {
                "NODE_ENV": JSON.stringify("production")
            }
        }),
        // 加署名
        new webpack.BannerPlugin('Copyright by Zero https://github.com/l-Lemon/blog')
    ]
}

package.json的 script 中加入

"build": "webpack --config webpack.pro.config.js"

运行 npm run build 根目录会生成 dist文件夹 和压缩后的代码。

  1. 抽离公共的webpack配置
    我们发现生产环境和开发环境中的webpack配置有很多相同的配置,为了维护性我们最好抽离出来。
    创建webapck.base.js文件来存我们公共配置
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
// 抽离css
const extractCss = new ExtractTextPlugin("style.css")
// html 模版
const htmlTemplate = new HtmlWebpackPlugin({template:'./src/index.html',favicon: './public/favicon.png'})
const config = {
    output:{
        path:path.resolve(__dirname,'dist'),
        filename:'bundle.[hash:4].js'
    },
    module:{
        rules:[
            {  
                test: /\.(woff|eot|ttf|svg|png|jpg)$/,  
                use: [  
                    {  
                        loader: 'url-loader',  
                        options: {  
                            limit: '1024' ,
                            name: '[name].[hash:4].[ext]'  
                        }                        
                    },  
                ]  
            },
            {  
                test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
                use: [  
                    {  
                        loader: 'url-loader',  
                        options: {  
                            limit: '1024',
                            name: '[name].[hash:4].[ext]'  
                        }  
                    },  
                ]  
            },
            {
                test: /\.(css|less)$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: ["css-loader","less-loader"]
                })
            },
            {
                test:/\.(js|jsx)$/,
                use:"babel-loader",
                exclude:/node_modules/
            }
        ]
    },
}

module.exports = {
    htmlTemplate,
    extractCss,
    config
}
  1. 重构开发环境配置
    修改开发环境的webpack.config.js
const path = require('path')
const baseConfig = require('./webpack.base')

module.exports = {
    entry:{
        main:['babel-polyfill','./src/index.js'],
    },
    ...baseConfig.config,
    plugins:[
        baseConfig.htmlTemplate,
        baseConfig.extractCss
    ],
    devServer:{
        contentBase: path.join(__dirname, "dist"),
        compress: true,
        port: 9000,
        proxy: {
            "/api": {
              target: "http://127.0.0.1:3000/",
              pathRewrite: {"^/api" : ""}
            }
          }
    }
}
  1. 重构生产环境配置
    修改开发环境的webpack.pro.config.js
const webpack = require('webpack')
const baseConfig = require('./webpack.base')

module.exports = {
    entry:{
        main:['babel-polyfill','./src/index.js'],
        // 将第三方库包单独打包,充分利用浏览器缓存        
        vendors: ['react','react-dom','react-router-dom','whatwg-fetch']
    },
    ...baseConfig.config,
    devtool: false,
    plugins:[
        // html 模板插件
        baseConfig.htmlTemplate,
        // 启用作用域提升,让代码文件更小、运行的更快
        new webpack.optimize.ModuleConcatenationPlugin(),
        // 提取公共代码vendors
        new webpack.optimize.CommonsChunkPlugin({
            name:'vendors',
            filename:'[name].[hash:4].js'
        }),
        // 抽离出css
        baseConfig.extractCss,
        // 压缩js代码
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false,
                drop_console: true,
                pure_funcs: ['console.log']
            }
        }),
        // 定义全局常量
        new webpack.DefinePlugin({
            "process.env": {
                "NODE_ENV": JSON.stringify("production")
            }
        }),
        // 加署名
        new webpack.BannerPlugin('Copyright by Zero https://github.com/l-Lemon/blog')
    ]
}

好了,现在我们再来试试npm run devnpm run build命令,没问题都可以完美运行。

总结


这篇文章我们介绍了生产环境webpack的配置,并且抽出了公共配置,重构了开发环境和生产环境的配置。

下篇我们来介绍实现单元测试

系列文章


  1. 从零开始React项目架构(一)
  2. 从零开始React项目架构(二)
  3. 从零开始React项目架构(三)

源码


React项目架构