web icon indicating copy to clipboard operation
web copied to clipboard

fix(rollup-plugin-import-meta-assets): completely overwrite import.meta.url

Open cprecioso opened this issue 3 years ago • 1 comments

This removes the duplicated import.meta.url in the output, like this:

 // Pre-bundling code
 new URL("./some-internal-path.png", import.meta.url)
 
 // Bundled code in ESM output 
-new URL(new URL("asset/bundled-asset.png", import.meta.url).href, import.meta.url) 
+new URL(new URL("asset/bundled-asset.png", import.meta.url).href) 

 // Bundled code in CJS output 
 new URL(
   "undefined" == typeof document
     ? new (require("url").URL)(
         "file:" + __dirname + "/assets/InterLatin-b0e9bc2a.woff2"
       ).href
     : new URL(
         "assets/InterLatin-b0e9bc2a.woff2",
         (document.currentScript && document.currentScript.src) ||
           document.baseURI
       ).href
-, import.meta.url); // Uncaught SyntaxError: Cannot use 'import.meta' outside a module
+);

Why

This way, it should work exactly the same (Rollup makes sure we have import.meta.url or something similar to base our URL on); but the second import.meta gets eliminated, which reduces size, repetition, and most of all, doesn't trigger an error in Common JS modules.

What I did

  1. Updated the overwrite function

    // Before
    new URL("myFile.tx", import.meta.url)
    //      |---------|
    //      Only this part was overwritten
    
    // After
    new URL("myFile.tx", import.meta.url)
    //      |--------------------------|
    //      Now everything is overwritten
    
  2. Updated tests

I made it a minor change as it should supposedly not modify the functionality of the plugin, but maybe it should be a major as it modifies its output?

cprecioso avatar Jun 07 '22 13:06 cprecioso

🦋 Changeset detected

Latest commit: 6ab8a0ad4ff5bbac28de088519cf42c2b8eae7d2

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@web/rollup-plugin-import-meta-assets Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

changeset-bot[bot] avatar Jun 07 '22 13:06 changeset-bot[bot]