Skip to content

Instantly share code, notes, and snippets.

@surma
Last active July 28, 2020 13:13
Show Gist options
  • Select an option

  • Save surma/519428064297de8a32639d1ec1acc720 to your computer and use it in GitHub Desktop.

Select an option

Save surma/519428064297de8a32639d1ec1acc720 to your computer and use it in GitHub Desktop.

Revisions

  1. surma created this gist Jul 28, 2020.
    3 changes: 3 additions & 0 deletions .gitignore
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,3 @@
    build
    node_modules
    package-lock.json
    1 change: 1 addition & 0 deletions dynamic.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    console.log("lol");
    1 change: 1 addition & 0 deletions input.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    import("./dynamic.js");
    6 changes: 6 additions & 0 deletions package.json
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,6 @@
    {
    "name": "rollup-purge",
    "scripts": {
    "build": "rollup -c"
    }
    }
    43 changes: 43 additions & 0 deletions rollup.config.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    const MARKER = "myimport:";

    export default {
    input: "input.js",
    output: {
    dir: "build",
    format: "esm"
    },
    preserveEntrySignatures: false,
    plugins: [
    {
    resolveId(id) {
    if (id === MARKER) {
    return MARKER;
    }
    },
    load(id) {
    if (id === MARKER) {
    return `export function myimport(id){}`;
    }
    },
    transform(code, id) {
    if (id === MARKER) {
    return;
    }
    return `
    import {myimport} from "${MARKER}"; ${code}
    // It works with the following line
    // self[Symbol()] = myimport;
    `;
    },
    renderDynamicImport(moduleId) {
    if (moduleId === MARKER) {
    return;
    }
    return {
    left: "myimport(",
    right: ", import.meta.url)"
    };
    }
    }
    ]
    };