[js/web] make ort-web export compatible with webpack #22196
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This PR fixes a few problems when using onnxruntime-web as dependency in webpack.
Context
While onnxruntime-web fully supports ESM since v1.19, there are still issues reported for consuming onnxruntime-web in some frameworks like Next.js. After some investigation, one of the root causes is identified: onnxruntime-web depends on runtime evaluation of
import.meta.url
to create workers for proxy feature and web assembly multi-threading, but the runtime evaluation ofimport.meta.url
is not supported by default for the mainstream version of the bundlers like Webpack.Back to the old days when browsers didn't support
import.meta.url
, the bundlers encourages to use it in the form of:This URL will be pre-processed at compile time to be replaced by a modified URL (can be script/asset/...) and it worked perfectly with bundler to resolve a lot of resource bundling requirement.
Today, most of the browsers support evaluating
import.meta.url
at runtime. It is expected to return the runtime URL of the current running script. This feature helps ESM scripts to load (both statically and dynamically) resources in a "modern" way. Unfortunately, this is conflicted with the "old way" that the bundler's default behavior.Issues like #22113 is exactly caused by this problem.
Workaround
Ideally the solution should be provided by the bundler. However considering the wide usage of webpack and its ecosystem, we need to make a workaround to let onnxruntime-web working with bundlers with default configuration, before webpack fully supports ESM. (it is going to be a while for Webpack itself and features (eg. HMR))
The workaround is simple:
This workaround works with the "bundled" build and tested with the following usage: