Is it possible to exclude a module from a require optimizer build config but have that module and it's dependencies be optimized separately?

StackOverflow https://stackoverflow.com/questions/15396080

  •  23-03-2022
  •  | 
  •  

Domanda

So the situation is the following:

I have a bunch of page specific js files which I'm optimizing using r.js.

99% of them define a a module called core.js as a dependency. Core has 5 dependencies of it's own.

I wanted to leverage caching by excluding core from the optimised versions of the page js files.

So in my build.js I tried something along the lines of:

modules: [
  {
     name : 'modules/core'
  },
  {
     name: 'homepage',
     exclude : ['modules/core']
  }
]

When I run the optimiser it optimises both modules/core & homepage just fine.

Going to a page that uses homepage.js the issue is that: core.js & it's dependencies are being loaded in individually, leading to 7 requests instead of 2.

In the above example, what I'm trying to achieve is: have homepage.js and it's dependencies optimised into a single file and have it load in an optimised version of core.js rather then loading in the core.js and it's dependencies separately.

Is that even possible?

È stato utile?

Soluzione

You have two options, after a build either:

1) modify the top level loading such that modules/core is loaded before any other loading:

require(['modules/core'], function () {
  //Now do normal require stuff in here
});

Use another nested require() call in there for homepage if you see its modules requested before homepage finishes loading.

2) Insert a require.config block that points all the modules in core to the core file. requirejs will only fetch the core.js file once when multiple module IDs all point to it:

require.config({
  paths: {
    'mod/one': 'modules/core',
    'mod/two', 'modules/core',
    ...
  }
});

Or see this kind of example project that sets up loading a common and then a page-specific layer, but works without having to do a source modification after a build (just uses a variation of #1, but sets it up to work in source form):

https://github.com/requirejs/example-multipage

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top