Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indirectly reference remote Javascript URL

We want to use Rollup with Angular 4/Typescript and NPM We have the following requirement within our company:

  • Certain teams create JS libraries which need to be centralized (like a CDN)
  • These libraries are behind a remote URL and should not exist locally within the application (the reason is that those libraries change too often)
  • The consumer of the library (application) installs a npm package to use the library
  • The locally installed npm package contains a Javascript facade file or bundle which puts a remote link to the JS library existing behind a remote URL
  • The npm package also contains a Typescript definition file
  • The goal is that the consumer doesn't need to add a script tag with an URL (he shouldn't be aware of this)
  • The locally installed Javascript file could be bundled together with the application code
  • New versions of the library would be backwards compatible if possible

What is the best way to achieve this using Typescript/Javascript/NPM/Rollup? We would use ES2015 syntax transpiled to commonJS syntax.

like image 314
stephan.peters Avatar asked May 29 '17 16:05

stephan.peters


1 Answers

I don't think rollup has something similar to webpack dll plugin, so, my answer may appear unrelated but I think you could assume it as a good starting point and start looking for something similar in rollup.

a library living in a CDN:

  1. Create a DLL with its corresponding DLL Reference which exactly describes how to require the exported modules.
  2. Use a self-explaining path and keep it consistent like https://cdn.mydomain.com/<libraryName>/<version>/<libraryName>.{js,json,d.ts} (the requester should add ?<cacheBustingUID> to avoid client caching issues). In addition to the normal versioning, I also suggest you to use a keyword latest for the version field, this to achieve an always true path which points to the latest version of the bundle: (https://cdn.mydomain.com/foo/1.0.0/foo.{js,json,d.ts}, and https://cdn.mydomain.com/foo/latest/foo.{js,json,d.ts}).
  3. Resolve all the files and start the dev server (mind that webpack allows to return a promise as a config)
module.exports = env => {
  const libs = ((name, version, exts) => (
    exts.map(ext => `https://cdn.mydomain.com/${name}/${version}/${name}.${ext}`)
  ))('foo', 'latest', ['js', 'd.ts', 'json'])

  return Promise
    .all(libs.map(fetch))
    .then([library, definitions, DLLReference] => {
      // what to do?
      // you can also inject the dynamic paths through `webpackDefinePlugin`
    })
}
like image 86
Hitmands Avatar answered Sep 22 '22 17:09

Hitmands