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

前言


使用当前的webpack配置能不能打包构建项目呢?固然能够,但这不是咱们想要的,因此,让咱们来看一看生产环境须要怎么配置webpack吧javascript

开发


  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 中加入css

"build": "webpack --config webpack.pro.config.js"
复制代码

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

  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命令,没问题均可以完美运行。java

总结


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

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

系列文章


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

源码


React项目架构webpack

相关文章
相关标签/搜索