webpack打包懒加载

lazyload

https://webpack.js.org/guides/lazy-loading/

懒加载 -- 按需加载。

Lazy, or "on demand", loading is a great way to optimize your site or application. This practice essentially involves splitting your code at logical breakpoints, and then loading it once the user has done something that requires, or will require, a new block of code. This speeds up the initial load of the application and lightens its overall weight as some blocks may never even be loaded.

webpack solution

https://webpack.js.org/migrate/3/#code-splitting-with-es2015

Code Splitting with ES2015

In webpack 1, you could use require.ensure() as a method to lazily-load chunks for your application:

require.ensure([], function(require) {
  var foo = require(‘./module‘);
});

The ES2015 Loader spec defines import() as method to load ES2015 Modules dynamically on runtime. webpack treats import() as a split-point and puts the requested module in a separate chunk. import() takes the module name as argument and returns a Promise.

function onClick() {
  import(‘./module‘).then(module => {
    return module.default;
  }).catch(err => {
    console.log(‘Chunk loading failed‘);
  });
}

Good news: Failure to load a chunk can now be handled because they are Promise

require.ensure

https://webpack.js.org/api/module-methods/#requireensure

require.ensure() is specific to webpack and superseded by import().

require.ensure(
  dependencies: String[],
  callback: function(require),
  errorCallback: function(error),
  chunkName: String
)

Split out the given dependencies to a separate bundle that that will be loaded asynchronously. When using CommonJS module syntax, this is the only way to dynamically load dependencies. Meaning, this code can be run within execution, only loading the dependencies if certain conditions are met.

This feature relies on Promise internally. If you use require.ensure with older browsers, remember to shim Promise using a polyfill such as es6-promise or promise-polyfill.

var a = require(‘normal-dep‘);

if ( module.hot ) {
  require.ensure([‘b‘], function(require) {
    var c = require(‘c‘);

    // Do something special...
  });
}

The following parameters are supported in the order specified above:

  • dependencies: An array of strings declaring all modules required for the code in the callback to execute.
  • callback: A function that webpack will execute once the dependencies are loaded. An implementation of the require function is sent as a parameter to this function. The function body can use this to further require() modules it needs for execution.
  • errorCallback: A function that is executed when webpack fails to load the dependencies.
  • chunkName: A name given to the chunk created by this particular require.ensure(). By passing the same chunkName to various require.ensure() calls, we can combine their code into a single chunk, resulting in only one bundle that the browser must load.

Although the implementation of require is passed as an argument to the callback function, using an arbitrary name e.g. require.ensure([], function(request) { request(‘someModule‘); }) isn‘t handled by webpack‘s static parser. Use require instead, e.g. require.ensure([], function(require) { require(‘someModule‘); }).

import()

import(‘path/to/module‘) -> Promise

Dynamically load modules. Calls to import() are treated as split points, meaning the requested module and it‘s children are split out into a separate chunk.

The ES2015 Loader spec defines import() as method to load ES2015 modules dynamically on runtime.

if ( module.hot ) {
  import(‘lodash‘).then(_ => {
    // Do something with lodash (a.k.a ‘_‘)...
  });
}

This feature relies on Promise internally. If you use import() with older browsers, remember to shim Promise using a polyfill

require (amd-version)

https://webpack.js.org/api/module-methods/#require-amd-version

require(dependencies: String[], [callback: function(...)])

Similar to require.ensure, this will split the given dependencies into a separate bundle that will be loaded asynchronously. The callback will be called with the exports of each dependency in the dependencies array.

This feature relies on Promise internally. If you use AMD with older browsers (e.g. Internet Explorer 11), remember to shim Promise using a polyfill such as es6-promise or promise-polyfill.

require([‘b‘], function(b) {
  var c = require(‘c‘);
});

There is no option to provide a chunk name.

external NPM module -- bundle-loader

https://www.npmjs.com/package/bundle-loader

https://github.com/ruanyf/webpack-demos#demo08-html-webpack-plugin-and-open-browser-webpack-plugin-source

Another way of code splitting is using bundle-loader.

// main.js

// Now a.js is requested, it will be bundled into another file
var load = require(‘bundle-loader!./a.js‘);

// To wait until a.js is available (and get the exports)
//  you need to async wait for it.
load(function(file) {
  document.open();
  document.write(‘<h1>‘ + file + ‘</h1>‘);
  document.close();
});

require(‘bundle-loader!./a.js‘) tells Webpack to load a.js from another chunk.

Now Webpack will build main.js into bundle.js, and a.js into 0.bundle.js.

others lazy load

https://webpack.js.org/guides/lazy-loading/

Frameworks

Many frameworks and libraries have their own recommendations on how this should be accomplished within their methodologies. Here are a few examples:


Further Reading

reference:

https://github.com/amdjs/amdjs-api

https://github.com/yongningfu/webpa_ensure

https://github.com/yongningfu/webpack_package

原文地址:https://www.cnblogs.com/lightsong/p/10534644.html

时间: 2024-10-25 06:59:17

webpack打包懒加载的相关文章

记一次webpack打包样式加载问题

今天是周六. 我过来加班了. 是因为一个属性问题. 俗话说一杯茶一包烟一个bug改一天 感觉这句话就是特意为我准备的(我加班的时候喝奶茶,抽烟,而且就一个bug.哈哈哈哈哈哈哈哈哈哈或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或或) 言归正传,说下webpack打包问题,刚到新工作和大佬们一起做ts + vue + vant的项目.(我之前不写ts,其实差不多,就是命名语法等问题) 我们一起撸代码,一直是在本地run serve的本地是

解决vue-cli webpack打包后加载资源的路径问题

vue项目,访问打包后的项目,输入路径后,页面加载空白.这时会有两类问题,都是路径问题. 1.一个是css,js,ico等文件加载不到,是目录里少了dist 打开页面时一片空白 解决办法: 前端精品教程:百度网盘下载 config/index.js文件的build->assetsPublicPath的默认值改为 './' assetsPublicPath:资源的根目录.这个是通过http服务器运行的url路径.因为webapp和static中间还有层dist,所以要用'./' 2.另一个就是单纯

vue+webpack实现懒加载的三种方式

实现方式: 1.webpack method require.ensure([''], callback, chunkName) ; 2.es6 motehod import() import().then() import(/* webpackChunkName: async-chunk-name */ /* webpackMode: lazy */ modulename) 需要安装bable插件 syntax-dynamic-import,因为import只能出现在页面顶部 具体实现: 第一

vue 组件按需引用,vue-router懒加载,vue打包优化,加载动画

当打包构建应用时,Javascript 包会变得非常大,影响页面加载.如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了. 结合 Vue 的 异步组件 和 Webpack 的 code splitting feature, 轻松实现路由组件的懒加载. 我们要做的就是把路由对应的组件定义成异步组件 const Foo = resolve => { // require.ensure 是 Webpack 的特殊语法,用来设置 code-split

vue2.x 路由懒加载 优化打包体积

当打包构建应用时,Javascript 包会变得非常大,影响页面加载.如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了. 结合 Vue 的异步组件和 Webpack 的代码分割功能,轻松实现路由组件的懒加载. 首先,可以将异步组件定义为返回一个 Promise 的工厂函数 (该函数返回的 Promise 应该 resolve 组件本身): const Foo = () => Promise.resolve({ /* 组件定义对象 */ })

The way of Webpack learning (III.) -- codeSplitting &amp; lazyLoding(代码分割和路由懒加载)

代码分割:对于一个大型的web项目来说,如果为了减少http请求,只打包出一个bundle.js文件,那么只要我们的需求修改了一点点,整个bundle.js都需要重新加载,得不偿失.所以我们不妨把代码分割成一块一块的,按需加载,而且还能利用浏览器缓存机制,如果文件没有修改,直接从缓存读取.也就是说,代码分割就是把代码切成很多块(chunk). 懒加载:按需加载,页面需要什么文件我才去加载什么文件.我现在只知道应用在路由懒加载中,就是根据路由,按需加载不同的文件. 在上一章节提到使用Commonc

vue-router和webpack懒加载,页面性能优化篇

在vue单页应用中,当项目不断完善丰富时,即使使用webpack打包,文件依然是非常大的,影响页面的加载.如果我们能把不同路由对应的组件分割成不同的代码块,当路由被访问时才加载对应的组件(也就是按需加载),这样就更加高效了.--引自vue-router官方文档 如何实现?? vue异步组件 vue-router配置路由,使用vue的异步组件技术,可以实现懒加载,代码如下:// 每个组件都会生成一个js文件 import Vue from 'vue' import Router from 'vue

前端项目首屏加速 gzip打包 路由懒加载 cdn资源优化

目前主流的Vue, React 等单页项目中 build 把所有开发遇到的代码打包在一起形成一个js和一个css, 服务器请求, 然后加载js, css 等依赖进行渲染. 因此会经常遇到,个人写的项目,打开十分缓慢,需要加载很长时间才能加载完毕. 就算不是白屏,做了loading处理 但还是会很影响体验 排除服务器带宽实在太低, 服务器压力实在太大, 文件的大小是速度的第一影响. gzip打包 gzip打包很好理解. 请求的东西可以通过压缩的方式, 到了客户端再解压 采用nginx即可 配置方案

vue路由懒加载

当打包构建应用时,javascript包会变得非常大,影响页面加载.如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了. 结合Vue的异步组件和webpack的code splitting feature,轻松实现路由组件的懒加载. 我们要做的就是把路由对应的组件定义成异步组件: const Foo = resolve => { // require.ensure 是webpack的特殊语法,用来设置code-split point // 代