Skip to content

Commit

Permalink
Implement transform loader helper
Browse files Browse the repository at this point in the history
  • Loading branch information
sebamarynissen committed May 31, 2024
1 parent 5615faa commit dcd55d3
Showing 1 changed file with 33 additions and 3 deletions.
36 changes: 33 additions & 3 deletions lib/create-esm-loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,16 @@ export default function createLoader(config = {}) {
// object we'll be exporting. If they were not specified, we do nothing.
const hooks = {};
const ctx = { options: void 0 };
bind(hooks, config, ctx, 'resolve');
bind(hooks, config, ctx, 'load');
const parsedConfig = normalizeConfig(config);
bind(hooks, parsedConfig, ctx, 'resolve');
bind(hooks, parsedConfig, ctx, 'load');

// The initialize hook is a bit different because if it's not specified,
// then we use a default hook.
if (typeof config.initialize === 'function') {
bind(hooks, config, ctx, 'initialize');
} else {
config.initialize = options => void (ctx.options = options);
hooks.initialize = options => void (ctx.options = options);
}

// Return the hooks at last.
Expand All @@ -31,3 +32,32 @@ function bind(hooks, config, ctx, hook) {
return fn.call(ctx, ...args);
};
}

// # normalizeConfig(config)
// Normalizes the configuration, meaning that if we find a `test` property,
// we'll automatically generate the corresponding `load()` hook.
function normalizeConfig(config) {
if (config.test) {
const { test, transform, load, ...rest } = config;
const match = typeof test === 'function' ? test : url => {
return test.test(new URL(url).pathname);
};
return {
async load(url, ctx, nextLoad) {
if (!match(url)) return nextLoad(url);
const { source } = await nextLoad(url, { format: 'module' });
const result = await transform(source);
return {
source: result,
format: 'module',
};
},
...rest,
};
} else {

// Return as is otherwise.
return config;

}
}

0 comments on commit dcd55d3

Please sign in to comment.