[聚焦Webpack]10 webpack使用 - 图1webapck是什么?学习重点:在于配置和使用(工具)

  1. 前端代码为何要进行构建和打包? | 代码层面 :
    - 体积更小(Tree-Shaking、压缩、合并, 加载更快
    - 编译高级语言或语法(TS、ES6+、模块化、scss)
    - 兼容性和错误检查(Polyfill、postcss、eslint)
    | 研发流程:
    - 高效的开发环境
    - 统一的构构建流程和产出标准
    - 集成公司构建规范(提测、上线)
    | | —- | —- |

  2. module、chunk、bundle 分别什么意思, 有何区别?
    3. loader和plugin的区别?
    4. webpack 如何实现懒加载?
    5. webpack 常⻅性能优化?
    6. babel-runtime和babel-polyfill的区别?

webpack使用优化

1. 使用别名。 alise

  1. resolve: {
  2. alias: {
  3. '@views': path.resolve(__dirname, 'src/views'),
  4. moment: 'moment/min/moment-width-locales.min.js'
  5. }
  6. }

2. 忽略对已知模块解析。noParse 实践??

过滤不需要解析的文件,比如打包的时候依赖了三方库(jquyer、lodash)等,而这些三方库里面没有其他依赖,可以通过配置noParse不去解析文件,提高打包效率
RegExp [RegExp]|``function(resource) | string [string]

  1. module: {
  2. noParse: [/moment-with-locales/],
  3. noParse: /jquery|lodash/,
  4. noParse: (content) => /jquery|lodash/.test(content)
  5. }

3. 将模块暴露到全局,expose-loader、ProvidePlugin

3.1 expose-loader

  1. yarn add expose-loader --dev
  2. module: {
  3. loaders: [
  4. { test: require.resolve("jquery"), loader: "expose-loader?$" }
  5. ]
  6. }
  7. // window.$ is then available in the browser console
  8. require("expose-loader?$!jquery");

3.2 ProvidePlugin

  1. plugins: [
  2. new webpack.ProvidePlugin({
  3. $: 'jquery',
  4. jQuery: 'jquery'
  5. });
  6. ]
  7. // $ is automatically set to the exports of module "jquery"
  8. $('#item')

4. 提取公共代码。webpack.optimize.CommonsChunkPlugin

  1. entry: {
  2. vendor: ['jquery', 'other-lib'],
  3. },
  4. plugins: [
  5. new webpack.optimize.CommonsChunkPlugin({
  6. name: 'commons',
  7. // (公共 chunk(commnon chunk) 的名称)
  8. filename: 'commons.js',
  9. // (公共chunk 的文件名)
  10. // minChunks: 3,
  11. // (模块必须被3个 入口chunk 共享)
  12. // chunks: ["pageA", "pageB"],
  13. // (只使用这些 入口chunk)
  14. }),
  15. // 明确第三方chunk
  16. new webpack.optimize.CommonsChunkPlugin({
  17. name: 'vendor',
  18. // filename: "vendor.js"
  19. filename: "[name].[hash:8].js"
  20. // (给 chunk 一个不同的名字)
  21. minChunks: 3,
  22. // (随着 entry chunk 越来越多,
  23. // 这个配置保证没其它的模块会打包进 vendor chunk)
  24. chunks: ['jquery', 'lodash']
  25. })
  26. ]

5. 配置全局开关 webpack.DefinePlugin

  1. plugins: [
  2. new webpack.DefinePlugin({
  3. // Definitions...
  4. DEBUG: true
  5. });
  6. ]
  7. const Constant = {
  8. API_HOST: DEBUG ? "http://192.169.2.187" : ""
  9. }

6. 单独打包CSS

  1. yarn add extract-text-webpack-plugin --dev
  2. const ExtractTextPlugin = require("extract-text-webpack-plugin");
  3. module.exports = {
  4. module: {
  5. rules: [
  6. {
  7. test: /\.css$/,
  8. use: ExtractTextPlugin.extract({
  9. fallback: "style-loader",
  10. use: "css-loader"
  11. })
  12. }
  13. ]
  14. },
  15. plugins: [
  16. new ExtractTextPlugin("styles.css"),
  17. ]
  18. }

参考文献:
Webpack性能优化
css单独打包