react项目实战(权限模块开发八)js文件分开打包

来源:互联网 发布:关于清朝的纪录片 知乎 编辑:程序博客网 时间:2024/05/26 17:47

才开发几个界面就发现打包出的index.js文件就有700多kb了,由于部分插件的js文件是不会变化的,单独打包可以充分利用浏览器的缓存功能。

第一步:在项目跟目录下面添加一个webpack.config.js文件

这里写图片描述

第二步:为了将原有的js分开打,需要修改entry的指定.。由于我的项目用到了jquery,所以将jquery单独达成一个独立文件,再将react的相关组件打包成vendors.js。

webpackConfig.entry={    "index": "./src/index.js",    vendor: vendors,    jquery:["jquery"]  }

第三步:指定插件引用信息:

  webpackConfig.plugins.push(new webpack.optimize.CommonsChunkPlugin({    names: ["jquery","vendor"],    minChunks: Infinity  }));

config文件的全部内容如下:

var path = require('path');var ROOT_PATH = path.resolve(__dirname);var APP_PATH = path.resolve(ROOT_PATH, 'src/');var webpack=require('webpack');var CompressionWebpackPlugin = require('compression-webpack-plugin');const vendors = [  'react',  'react-dom',  'react-redux',  'react-router',  'react-router-redux',  'redux',];//将jquery单独打包,将react的相关组件单独打包module.exports = function (webpackConfig, env) {  webpackConfig.entry={    "index": "./src/index.js",    vendor: vendors,    jquery:["jquery"]  }  webpackConfig.plugins.push(new CompressionWebpackPlugin({ //gzip 压缩    asset: '[path].gz[query]',    algorithm: 'gzip',    test: new RegExp(      '\\.(js|css)$'    //压缩 js 与 css    ),    threshold: 10240,    minRatio: 0.8  }));  webpackConfig.plugins.push(new webpack.optimize.CommonsChunkPlugin({    names: ["jquery","vendor"],    minChunks: Infinity  }));  return webpackConfig;}

这里是将js文件再压缩成gzip格式。

  webpackConfig.plugins.push(new CompressionWebpackPlugin({ //gzip 压缩    asset: '[path].gz[query]',    algorithm: 'gzip',    test: new RegExp(      '\\.(js|css)$'    //压缩 js 与 css    ),    threshold: 10240,    minRatio: 0.8  }));

第四步:修改下public/index.html文件内容,因为我们将相应插件是单独打包自然我们需要额外的引用相应的js文件,注意要将vendor.js放在第一位,如果把jquery放在第一位,会报错误

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport" content="width=device-width, initial-scale=1">  <title>Dva Demo</title>  <link rel="stylesheet" href="index.css" /></head><body><div id="root"></div><script src="vendor.js"></script><script src="jquery.js"></script><script src="index.js"></script></body></html>

ok可以启动试试,运行下 npm run build看下打包的结果:

这里写图片描述

阅读全文
0 0
原创粉丝点击