简体   繁体   English

使用Webpack和ocLazyLoad进行代码拆分/延迟加载

[英]Code splitting/Lazy load with Webpack & ocLazyLoad

I know there are solutions out there to retrieve via javascript using System.import , however I want to use the directive version so we don't have to create a controller for every single template. 我知道有一些解决方案可以使用System.import通过javascript进行检索,但是我想使用指令版本,因此我们不必为每个模板都创建一个控制器。

What I'm trying to achieve is extracting a list of all files sent as an entry file, with a specific extension, and get their bundled name. 我要实现的目的是提取作为入口文件发送的所有文件的列表,并带有特定扩展名,并获取其捆绑名称。

Let's say I have 3 files for simplicity: 为了简单起见,假设我有3个文件:

module-a.lazy.js
module-b.lazy.js
main.entry.js

Let's say my entry points and output are defined like so: 假设我的入口点和输出定义如下:

var config = {
    entry: {
        module-a: "./module-a.lazy.js",
        module-b: "./module-b.lazy.js",
        bundle: "./main.entry.js"
    },
    output: {
        filename: "[name]-[hash:4].js",
        path : '/build'
    }
}

Obviously I'm going to end up with 3 files in my build folder, each with a custom dynamic hash in it's filename which i cannot type into the ocLazyLoad directive. 显然,我最终将在构建文件夹中包含3个文件,每个文件的文件名中都包含一个自定义动态哈希,因此我无法在ocLazyLoad指令中键入该文件。

In the main.entry.js file, I have a constant setup, which I'd like to replace with the output names of the lazy files. 在main.entry.js文件中,我有一个恒定的设置,我想用惰性文件的输出名称替换。

angular.module('demo', [])
    .constant('lazies', '%lazyfilenamehere%');

Expected output would be something like this: 预期的输出将是这样的:

angular.module('demo', [])
    .constant('lazies', ['/build/module-a.lazy-af34.js','/build/module-b.lazy-fdg3.js']);

Once I can obtain the output path names and store them in the main bundle, I can easily decorate the original ocLazyLoad directive to first search this array by a partial string, when matched it can return the whole filename and request it as normal. 一旦获得输出路径名并将其存储在主捆绑包中,就可以轻松装饰原始的ocLazyLoad指令以首先通过部分字符串搜索此数组,匹配时它可以返回整个文件名并正常请求它。

You don't even need to specify entrypoints, they will be created automagically once you start using dynamic imports. 您甚至不需要指定入口点,一旦开始使用动态导入,它们就会自动创建。 Use something like that: 使用类似的东西:

angular.module('demo', [])
        .constant('lazies', {
    'module-a' : () => import('module-a'), 
    'module-b' : () => import('module-b')
});

Than base your directive on ocLazyLoad and get your lazy module just in time with exact match. 比将指令基于ocLazyLoad并及时获得完全匹配的惰性模块。

UPD: I started to think probably it's possible to generate a set of directives based on module names. UPD:我开始考虑可能有可能基于模块名称生成一组指令。 Than you can simply use them anywhere you want! 比起您可以在任何需要的地方简单地使用它们!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM