您的位置:首页 > Web前端 > React

React多页面应用5(webpack生产环境配置,包括压缩js代码,图片转码等)

2018-01-02 10:26 1141 查看




本教程总共7篇,每日更新一篇,请关注我们!你可以进入历史消息查看以往文章,也敬请期待我们的新文章!

1.React多页面应用1(webpack开发环境搭建,包括Babel、热更新等) ----2017.12.28

2.React多页面应用2(处理CSS及图片,引入postCSS及图片处理等)----2017.12.29

3.React多页面应用3(webpack性能提升,包括打包性能、提取公共包等)----2017.12.30

4.React多页面应用4(webpack自动化生成多入口页面)----2017.12.31

5.React多页面应用5(webpack生产环境配置,包括压缩js代码,图片转码等)----2018.01.01

6.React多页面应用6(gulp自动化发布到多个环境,生成版本号,打包成zip等)----2018.01.02

7.React多页面应用7(引入eslint代码检查)----2018.01.03

开发环境:Windows 8,node v8.9.1,npm 5.5.1,WebStorm 2017.2.2

我们之前课程讲的都是开发环境的配置,今天我们来讲下,辛辛苦苦写的代码,如何优雅的打包成生产环境代码?

生产环境代码需要有几个特点:

文件体积尽量的小

14944

浏览器缓存!如果修改,如何让浏览器重新拉取

请求数尽量少

我们带着这几个目的,来配置我们的webpack生产环境!

首先我们安装必要的依赖
npm i -D html-webpack-plugin optimize-css-assets-webpack-plugin extract-text-webpack-plugin url-loader file


新建 webpack.prod.conf.js

我们把文件打包到 根目录下 pc文件夹下,当然 你可以自定义这个文件夹名称

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const baseWebpackConfig = require("./webpack.base.conf");
const webpackFile = require('./webpack.file.conf');
const entry = require("./webpack.entry.conf");
const webpackCom = require("./webpack.com.conf");

let config = merge(baseWebpackConfig, {
output: {
path: path.resolve(webpackFile.proDirectory),
       filename: 'js/[name].[chunkhash:8].js',
       chunkFilename: "js/[name]-[id].[chunkhash:8].js",
   },
   plugins: [
// 设置生产环境
       new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
           }
}),
       /* common 业务公共代码,vendor引入第三方 */
       new webpack.optimize.CommonsChunkPlugin({
name: ["common", "vendor"],
       }),
       /* 防止 vendor hash 变化 */
       // extract webpack runtime and module manifest to its own file in order to
       // prevent vendor hash from being updated whenever app bundle is updated
       new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
           chunks: ['vendor']
}),
       // extract css into its own file
       new ExtractTextPlugin('css/[name].[contenthash:8].css'),
       // Compress extracted CSS. We are using this plugin so that possible
       // duplicated CSS from different components can be deduped.
       new OptimizeCSSPlugin({
assetNameRegExp: /\.css$/g,
           cssProcessor: require('cssnano'),
           cssProcessorOptions: {
discardComments: {removeAll: true},
               // 避免 cssnano 重新计算 z-index
               safe: true
            },
           canPrint: true
        }),
       /*压缩js代码*/
       new webpack.optimize.UglifyJsPlugin({
output: {
comments: false/*删除版权信息*/
           },
           compress: {
warnings: false
            }
}),
   ],
   module: {
rules: [
{
test: /\.(js|jsx)$/,
               loader: 'babel-loader',
               exclude: /node_modules/,
           },
           {
test: /\.(css|pcss)$/,
               use: ExtractTextPlugin.extract({
fallback: "style-loader",
                   use: "css-loader!postcss-loader"
               })
},
           {
test: /\.(png|jpg|gif|ttf|eot|woff|woff2|svg)$/,
               loader: 'url-loader?limit=8192&name=[name].[hash:8].[ext]&publicPath=' + webpackFile.resourcePrefix + '&outputPath=' + webpackFile.resource + '/'
           },
           {
test: /\.swf$/,
               loader: 'file?name=js/[name].[ext]'
           }
]
}
});
let pages = entry;
for (let chunkName in pages) {
let conf = {
filename: chunkName + '.html',
       template: 'index.html',
       inject: true,
       title: webpackCom.titleFun(chunkName,pages[chunkName][1]),
       minify: {
removeComments: true,
           collapseWhitespace: true,
           removeAttributeQuotes: true
        },
       chunks: ['manifest', 'vendor', 'common', chunkName],
       hash: false,
       chunksSortMode: 'dependency'
   };
   config.plugins.push(new HtmlWebpackPlugin(conf));
}
/* 清除 pc */
config.plugins.push(webpackFile.cleanFun([webpackFile.proDirectory]));
/* 拷贝静态资源  */
webpackFile.copyArr.map(function (data) {
return config.plugins.push(data)
});
module.exports = config;


修改 package.json
"p": "SET BABEL_ENV=production && webpack --progress --colors --config config/webpack/webpack.prod.conf.js",


我们运行(这个p 是自定义的)
npm run p


运行结束后得到

文件都自动加上了 hash值,便于浏览器缓存,修改后这个hash会变,浏览器会重新获取.

大家发现没有 为什么没有 图片文件夹?

这是因为你的那张百度logo图片大小没有超过8192,被base64转码了,减少了一次请求.

当然你可以设置成精灵图,但是我们没有那么做.

这是文件夹里的文件结构

我们双击打开这两个html文件



一切正常! ok !

你可以把这个文件夹里的文件传到你的测试服务器上了!

下面我们会讲解,如何自动化发布到服务器上!

本文完 














禁止擅自转载,如需转载请在公众号中留言联系我们!

感谢童鞋们支持!

如果你有什么问题,可以在下方留言给我们!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息