当前位置:Gxlcms > JavaScript > webpack脚手架优化使用

webpack脚手架优化使用

时间:2021-07-01 10:21:17 帮助过:56人阅读

这次给大家带来webpack脚手架优化使用,webpack脚手架优化使用的注意事项有哪些,下面就是实战案例,一起来看一下。

优化类目

  1. 样式分离

  2. 第三方资源分离

  3. 区分开发环境

  4. 热更新

  5. 提取公共代码

1. CSS分离

  1. npm install extract-text-webpack-plugin -D

webpack.config.js

将css、less、sass文件单独从打包文件中分离

  1. + let cssExtract = new ExtractTextWebpackPlugin({
  2. + filename: 'css.css',
  3. + allChunks: true
  4. + });
  5. + let sassExtract = new ExtractTextWebpackPlugin('sass.css')
  6. + let lessExtract = new ExtractTextWebpackPlugin('less.css')

在webpack.config.js中单独添加规则,

  1. test:匹配处理文件的扩展名的正则表达式

  2. include/exclude手动指定必须处理的文件夹或屏蔽不需要处理的文件夹

  1. {
  2. test: /\.css$/,
  3. use: cssExtract.extract({
  4. fallback: "style-loader",
  5. use: ['css-loader?minimize','postcss-loader'],
  6. publicPath: "/dist"
  7. }),
  8. include:path.join(dirname,'./src'),
  9. exclude:/node_modules/
  10. },
  11. {
  12. test: /\.scss$/,
  13. use: sassExtract.extract({
  14. fallback: "style-loader",
  15. use: ["css-loader?minimize","sass-loader"],
  16. publicPath: "/dist"
  17. }),
  18. include:path.join(dirname,'./src'),
  19. exclude:/node_modules/
  20. },
  21. {
  22. test: /\.less$/,
  23. loader: lessExtract.extract({
  24. use: ["css-loader?minimize", "less-loader"]
  25. }),
  26. include:path.join(dirname,'./src'),
  27. exclude:/node_modules/
  28. },

然后运行webpack命令时报错

compilation.mainTemplate.applyPluginsWaterfall is not a function

Use Chunks.groupsIterable and filter by instanceof Entrypoint instead

研究得出结论:webpack升级到v4然而响应的插件没有升级的原故。

解决方法:安装指定版本的依赖

  1. "html-webpack-plugin": "^3.0.4"
  2. "extract-text-webpack-plugin": "^4.0.0-beta.0"

resolve

指定extension之后可以不用在require或是import的时候加文件扩展名,会依次尝试添加扩展名进行匹配

  1. resolve: {
  2. //引入模块的时候,可以不用扩展名
  3. extensions: [".js", ".less", ".json"],
  4. alias: {//别名
  5. "bootstrap": "bootstrap/dist/css/bootstrap.css"
  6. }
  7. }

监听文件修改

webpack模式下使用,webpack-dev-server模式不用,可以将watch改为false

  1. watchOptions: {
  2. ignored: /node_modules/,
  3. aggregateTimeout: 300, //监听到变化发生后等300ms再去执行动作,防止文件更新太快导致编译频率太高
  4. poll: 1000 //通过不停的询问文件是否改变来判断文件是否发生变化,默认每秒询问1000次
  5. }

提取公共代码

  1. optimization: {
  2. splitChunks: {
  3. cacheGroups: {
  4. commons: {
  5. chunks: "initial",
  6. minChunks: 2,
  7. maxInitialRequests: 5, // The default limit is too small to showcase the effect
  8. minSize: 0 // This is example is too small to create commons chunks
  9. },
  10. vendor: {
  11. test: /node_modules/,
  12. chunks: "initial",
  13. name: "vendor",
  14. priority: 10,
  15. enforce: true
  16. }
  17. }
  18. }
  19. }

分离react react-dom ant公共代码

方法一:externals

在页面上引入第三方资源库,然后使用externals防止将某些 import 的包(package)打包到 bundle 中,而是在运行时(runtime)再去从外部获取这些扩展依赖(external dependencies)。

  1. <script src="https://cdn.bootcss.com/react/16.4.0-alpha.0911da3/cjs/react.production.min.js"></script>
  2. <script src="https://cdn.bootcss.com/react-dom/16.4.0-alpha.0911da3/cjs/react-dom-server.browser.production.min.js"></script>
  3. externals: { 'react': 'React', 'react-dom': 'ReactDOM', // 提出ant design的公共资源, }

方法二:DLL

DLL在上篇文章中写过,但是打包后一直出现

后来才发现是页面上没有引入资源。。。。(我一直以为会webpack自动生成在页面上....)

在index.html文件中引入

  1. <script src="./vendor/react.dll.js"></script>

分离成功!上代码

webpack.base.js

  1. var path = require('path');
  2. var webpack = require('webpack');
  3. var ExtractTextWebpackPlugin = require("extract-text-webpack-plugin");
  4. const HtmlWebpackPlugin = require("html-webpack-plugin");
  5. const CleanWebpackPlugin = require('clean-webpack-plugin');
  6. const CopyWebpackPlugin = require('copy-webpack-plugin')
  7. let cssExtract = new ExtractTextWebpackPlugin({
  8. filename: 'css.css',
  9. allChunks: true
  10. });
  11. let sassExtract = new ExtractTextWebpackPlugin('sass.css')
  12. let lessExtract = new ExtractTextWebpackPlugin('less.css')
  13. module.exports = {
  14. entry:'./src/index.js',
  15. output: {
  16. path: path.resolve(dirname, './dist'),
  17. filename: 'bundle.[hash:8].js',
  18. publicPath: ''
  19. },
  20. resolve: {
  21. //引入模块的时候,可以不用扩展名
  22. extensions: [".js", ".less", ".json"],
  23. alias: {//别名
  24. "bootstrap": "bootstrap/dist/css/bootstrap.css"
  25. },
  26. modules: [path.resolve(dirname, 'node_modules')]
  27. },
  28. /* externals: {
  29. 'react': 'React',
  30. 'react-dom': 'ReactDOM',
  31. // 提出ant design的公共资源
  32. //'antd': 'antd',
  33. },*/
  34. devtool: 'source-map',
  35. devServer: {
  36. contentBase:path.resolve(dirname,'dist'),
  37. publicPath: '/',
  38. port: 8080,
  39. hot:true,
  40. compress:true,
  41. historyApiFallback: true,
  42. inline: true
  43. },
  44. watch: false, //只有在开启监听模式时,watchOptions才有意义
  45. watchOptions: {
  46. ignored: /node_modules/,
  47. aggregateTimeout: 300, //监听到变化发生后等300ms再去执行动作,防止文件更新太快导致编译频率太高
  48. poll: 1000 //通过不停的询问文件是否改变来判断文件是否发生变化,默认每秒询问1000次
  49. },
  50. optimization: {
  51. splitChunks: {
  52. cacheGroups: {
  53. commons: {
  54. chunks: "initial",
  55. minChunks: 2,
  56. maxInitialRequests: 5, // The default limit is too small to showcase the effect
  57. minSize: 0 // This is example is too small to create commons chunks
  58. },
  59. vendor: {
  60. test: /node_modules/,
  61. chunks: "initial",
  62. name: "vendor",
  63. priority: 10,
  64. enforce: true
  65. }
  66. }
  67. }
  68. },
  69. module: {
  70. rules:[
  71. {
  72. test: /\.js$/,
  73. use: {
  74. loader:'babel-loader',
  75. options: {
  76. presets: ['env','es2015', 'react'],
  77. }
  78. },
  79. include:path.join(dirname,'./src'),
  80. exclude:/node_modules/
  81. },
  82. {
  83. test: /\.css$/,
  84. use: cssExtract.extract({
  85. fallback: "style-loader",
  86. use: ['css-loader?minimize','postcss-loader'],
  87. publicPath: "/dist"
  88. }),
  89. include:path.join(dirname,'./src'),
  90. exclude:/node_modules/
  91. },
  92. {
  93. test: /\.scss$/,
  94. use: sassExtract.extract({
  95. fallback: "style-loader",
  96. use: ["css-loader?minimize","sass-loader"],
  97. publicPath: "/dist"
  98. }),
  99. include:path.join(dirname,'./src'),
  100. exclude:/node_modules/
  101. },
  102. {
  103. test: /\.less$/,
  104. loader: lessExtract.extract({
  105. use: ["css-loader?minimize", "less-loader"]
  106. }),
  107. include:path.join(dirname,'./src'),
  108. exclude:/node_modules/
  109. },
  110. {
  111. test: /\.(html|htm)/,
  112. use: 'html-withimg-loader'
  113. },
  114. {
  115. test: /\.(png|jpg|gif|svg|bmp|eot|woff|woff2|ttf)/,
  116. use: {
  117. loader:'url-loader',
  118. options:{
  119. limit: 5 * 1024,
  120. //指定拷贝文件的
输出目录 outputPath: 'images/' } } } ] }, plugins: [ //定义环境变量 new webpack.DefinePlugin({ development: JSON.stringify(process.env.NODE_ENV) }), new CleanWebpackPlugin(['dist']), cssExtract, lessExtract, sassExtract, new HtmlWebpackPlugin({ title: 'React Biolerplate by YuanYuan', template: './src/index.html', filename: `index.html`, hash: true }), new webpack.DllReferencePlugin({ manifest: path.join(dirname, 'vendor', 'react.manifest.json') }), new CopyWebpackPlugin([{ from: path.join(dirname,'vendor'),//静态资源目录源地址 to:'./vendor' //目标地址,相对于output的path目录 }]), /* new webpack.optimize.CommonsChunkPlugin({ name: 'common' // 指定公共 bundle 的名称。 + })*/ new webpack.HotModuleReplacementPlugin(), // 热替换插件 new webpack.NamedModulesPlugin() // 执行热替换时打印模块名字 ] };

webpack.config.js

  1. const path = require('path');
  2. const webpack = require('webpack');
  3. const merge = require('webpack-merge');//用来合并配置文件
  4. const base = require('./webpack.base');
  5. let other = '';
  6. //console.log(process.env.NODE_ENV )
  7. if (process.env.NODE_ENV == 'development') {
  8. other = require('./webpack.dev.config');
  9. } else {
  10. other = require('./webpack.prod.config');
  11. }
  12. //console.log(merge(base, other));
  13. module.exports = merge(base, other);
  14. webpack.prod.config.js
  15. const path = require('path');
  16. const webpack = require('webpack');
  17. const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
  18. module.exports = {
  19. output: {
  20. filename: 'bundle.min.js',
  21. },
  22. plugins: [
  23. new UglifyJSPlugin({sourceMap: true})
  24. ]
  25. }

原脚手架地址

优化后手架地址

相信看了本文案例你已经掌握了方法,更多精彩请关注Gxl网其它相关文章!

推荐阅读:

从dev到prd使用详解

webpack中dev-server使用步骤详解

以上就是webpack脚手架优化使用的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行