Skip to content
This repository has been archived by the owner on Apr 19, 2024. It is now read-only.

Commit

Permalink
Defined the initial approach
Browse files Browse the repository at this point in the history
  • Loading branch information
FlorianRappl committed Mar 23, 2020
1 parent eac2317 commit cf3a60c
Show file tree
Hide file tree
Showing 4 changed files with 90 additions and 8 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
- Implemented support for URLs
- Implemented support for local files
- Implemented lazy loading startup
- Provide `ready` function to check for loading
- Defined initial approach using *package.json*

## 0.1.0

Expand Down
68 changes: 68 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ Install the plugin via npm:
npm i parcel-plugin-import-maps
```

### Declaring Import Maps

You can now add a new key to your *package.json*: `importmap`. The key can either hold an `importmap` structure (see [specification](https://wicg.github.io/import-maps/)) or a reference to a valid JSON file holding the structure.

Example for the containing the structure in the *package.json*:
Expand Down Expand Up @@ -77,6 +79,72 @@ Most importantly, the plugin allows you to place scripts from other locations ea

For proper IDE (or even TypeScript) usage we still advise to install the respective package or at least its bindings locally.

### Loading Import Maps

The required import maps are loaded at startup *asynchronously*. Therefore, you'd need to wait before using them.

Unfortunately, in the current version this cannot be done implicitly (reliably), even though its desired for the future.

Right now the only way is to change code like (assumes `lodash` is used from an import map like above)

```js
//app.js
import * as _ from 'lodash';

const _ = require('lodash');

export const partitions = _.partition([1, 2, 3, 4], n => n % 2);
});
```

to be

```js
//app.js
import { ready } from 'importmap';

ready().then(() => {
const _ = require('lodash');
return {
partitions: _.partition([1, 2, 3, 4], n => n % 2),
};
});
```

or, alternatively (more generically),

```js
//index.js
import { ready } from 'importmap';

module.exports = ready().then(() => require('./app'));

//app.js
import * as _ from 'lodash';

const _ = require('lodash');

export const partitions = _.partition([1, 2, 3, 4], n => n % 2);
});
```

You could also trigger the loading already in the beginning, i.e.,

```js
//app.js
import 'importmap';

// ...
//other.js
import { ready } from 'importmap';

ready('lodash').then(() => {
// either load or do something with require('lodash')
});
```

where we use `ready` with a single argument to determine what package should have been loaded to proceed. This is the deferred loading approach. Alternatively, an array with multiple package identifiers can be passed in.

## Changelog

This project adheres to [semantic versioning](https://semver.org).
Expand Down
4 changes: 4 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
declare function setupImportMapsPlugin(bundler: any): void;

export = setupImportMapsPlugin;

declare module "importmap" {
export function ready(id?: string | Array<string>): Promise<void>;
}
24 changes: 16 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,14 @@ function createFile(dir, name, content) {
return path;
}

function getSourcePath(root, file) {
return `/${relative(root, file)}`;
}

function getImportFor(root, dir, file) {
if (!file.startsWith('http:') && !file.startsWith('https:')) {
const absPath = resolve(dir, file);
const relPath = relative(root, absPath);
return `import(${JSON.stringify(`/${relPath}`)})`;
const path = getSourcePath(root, resolve(dir, file));
return `import(${JSON.stringify(path)})`;
} else {
return `new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
Expand All @@ -81,6 +84,8 @@ function getImportFor(root, dir, file) {
}
}

let original;

module.exports = function(bundler) {
const root = bundler.options.rootDir;
const dir = getPackageDir(root);
Expand All @@ -91,7 +96,7 @@ module.exports = function(bundler) {
const modules = {};
const temp = resolve(__dirname, "_temp");
const resolver = bundler.resolver;
const gA = resolver.__proto__.getAlias;
const getAlias = original || (original = resolver.__proto__.getAlias);

if (!existsSync(temp)) {
mkdirSync(temp);
Expand Down Expand Up @@ -134,14 +139,17 @@ window.__registerImports([${keys.map(id => `{
load: () => ${getImportFor(root, dir, map.imports[id])},
}`).join(',')}]);
module.exports = function (cb) {
Promise.all(${JSON.stringify(keys)}.map(id => window.__resolveImport(id).loading)).then(cb);
exports.ready = function (id) {
const ids = Array.isArray(id) ? id : (id ? [id] : ${JSON.stringify(keys)});
return Promise.all(ids.map(id => window.__resolveImport(id).loading));
};
`
);

resolver.__proto__.getAlias = function(filename, dir, aliases) {
if (keys.includes(filename)) {
if (filename === 'importmap') {
return resolve(temp, 'index.js');
} else if (keys.includes(filename)) {
const m = modules[filename];

if (!m) {
Expand All @@ -157,7 +165,7 @@ module.exports = function (cb) {
return m;
}

return gA.call(resolver, filename, dir, aliases);
return getAlias.call(resolver, filename, dir, aliases);
};
}
};

0 comments on commit cf3a60c

Please sign in to comment.