Stream: ComponentizeJS

Topic: How to import addtional js modules


view this post on Zulip Richard Backhouse (Aug 23 2023 at 10:41):

If your top level js code requires additional modules that are not part of the wit how can they be imported? Currently 'componetize' will fail with

Import 'util' in source.js is not defined as a world import. Only component-defined imports can be used.

I was able to get this to work by modifying 'componentize.js' to add an additional option that adds a set of imports to the importWrappers array but I'm not sure this is the best approach to supporting this.

const httputil = await readFile('httputil.js', 'utf8');
const util = await readFile('util.js', 'utf8');
const uuid = await readFile('uuid.js', 'utf8');
const jsSource = await readFile('testjs.js', 'utf8');

const importWrappers = [
    [
        "util", util
    ],
    [
        "httputil", httputil
    ],
    [
        "uuid", uuid
    ]
];
const { component } = await componentize(jsSource, {
    witPath: resolve('./wit/'),
    enableStdout: false,
    debug: false,
    additionalImportWrappers: importWrappers,
});

view this post on Zulip Guy Bedford (Aug 23 2023 at 17:24):

@Richard Backhouse good question, we could effectively perform a bundling step with a JS bundler before running componentize, where the externals of the bundling would be the WIT imports.

One problem with this approach is if you make a typo or use the wrong import, it might be surprising why it attempts to find it in node_modules instead. But I think overall that would be the best approach here. I've posted an issue in https://github.com/bytecodealliance/componentize-js/issues/46 to track this.

When componentizing a JS application, we should including a JS bundler to build the JS file first before componentization. This could support both TypeScript as well as node_modules and local impor...

Last updated: Nov 22 2024 at 16:03 UTC