zoukankan      html  css  js  c++  java
  • [Webpack] Externalize Dependencies to be Loaded via CDN with webpack

    We can separate our custom application code from the common libraries we leverage, such as React and ReactDOM. In this lesson we'll configure webpack to treat React and ReactDOM as external dependencies. Then we'll update our HTML template to conditionally include the CDN links for those libraries for production builds.

    Why to do this?

    One of the main advantages of using a CDN is reduced latency, so if you cannot, for some reason, host your main bundle on a CDN, you can at least speed up loading of some dependencies. In addition to that, if you use a commonly used CDN, you can potentially take advantage of the browser's cached copy of React and ReactDOM from other sites that are also hosting from that CDN

    The reduced latency comes from the fact that a CDN will serve files from a POP (point of presence) that is geographically closer to the requester. The reduced latency is a pure physics problem of distance. This doesn't solve other network issues like congestion and throughput limits, but it's a step in the right direction.

    We only want to do this for production:

    // webpack.config.prod.js
    
    const merge = require('webpack-merge')
    const {BundleAnalyzerPlugin} = require('webpack-bundle-analyzer')
    const baseConfig = require('./webpack.config.base')
    
    module.exports = merge(baseConfig, {
      mode: 'production',
      plugins: [new BundleAnalyzerPlugin({
        analyzerMode: 'static',
        openAnalyzer: false,
        reportFilename: 'bundle_sizes.html'
      })],
      externals: {
        react: 'React',
        'react-dom': 'ReactDOM'
      }
    })

    We add 'exernals' prop, it is a key value pair, key is the package name, value is the variable name:

    import React from 'react'
    import ReactDOM from 'react-dom'

    Github

  • 相关阅读:
    Auto-Test 要点纪录(一)
    终端应用变身文件 MD5/SHA1 校验工具
    MD5 algorithm in Objective C
    iphone开发-SQLite数据库使用
    【React】354- 一文吃透 React 事件机制原理
    【Web技术】353- CDN 科普
    【CSS】352- 有趣的CSS弹跳动画
    【Vuejs】351- 带你解析vue2.0的diff算法
    【每周小回顾】7- 一起回顾上周精彩内容
    【Vuejs】350- 学习 Vue 源码的必要知识储备
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10554718.html
Copyright © 2011-2022 走看看