I am developing a node module that will be consumed by applications that use Webpack and Next.js. The node module uses microbundle
when building and publishing the module.
The module imports a 3rd party library and uses a different URL based on the environment. I'm just learning about how each processes imports at runtime and not entirely sure how this works. Ideally, I would like the application consuming our module to pass a host for the 3rd party library. However, using any conditionals or passing any variables as the host causes the following error: Error: Cannot find module https://example.com/library
.
Using tsc
to build my module all of the solutions below work, but microbundle
does something with dynamic imports causing the error.
This works
const importLibrary = async (env: 'dev' | 'prod'): Promise<LibraryType> => {
const devHost = 'https://example-dev.com'
const prodHost = 'https://example-prod.com'
if (env === 'dev') {
return await import(`${devHost}/library`)
}
return await import(`${prodHost}/library`)
}
Causes an error
// Using a conditional in host
const importLibrary = async (env: 'dev' | 'prod'): Promise<LibraryType> => {
const host = env === 'dev'
? 'https://example-dev.com'
: 'https://example-prod.com'
return await import(`${host}/library`)
}
// Passing prop from application
type HostType = 'https://example-dev.com' | 'https://example-prod.com'
const importLibrary = async (host: HostType): Promise<LibraryType> => {
return await import(`${host}/library`)
}
All options work in a vite application, but Next.js and Webpack(using CRA or CRACO to build) fail with the error I have above. Any help is greatly appreciated!
NOTE: I am simplifying my code, the actual code I am using does have a try statement. I do console.log
the error and return undefined if it can't be imported.