How do I get rollup to compile at runtime with Deno?

Viewed 426

I have the following Deno code...

import rollup from "https://unpkg.com/rollup/dist/es/rollup.js";
const inputOptions = {
    input: "./index.mjs"
}
const outputOptions = {
    format: "esm",
    sourcemap: "inline"
}

const build = async ()=>{
    const bundle = await rollup.rollup(inputOptions);
    const { output } = await bundle.generate(outputOptions);
    for (const chunkOrAsset of output) {
        if (chunkOrAsset.type === 'asset') {
            console.log('Asset', chunkOrAsset);
        } else{
            console.log('Chunk', chunkOrAsset.modules);
        }
    }
}

But when I try to run I get...

error: relative import path "path" not prefixed with / or ./ or ../ Imported from "https://unpkg.com/rollup@2.26.11/dist/es/rollup.js"

I also tried

import rollup from "https://unpkg.com/rollup";

but I get...

error: Uncaught SyntaxError: The requested module 'https://unpkg.com/rollup' does not provide an export named 'default'

finally I tried...

import * as rollup from "https://unpkg.com/rollup";

But I get...

error: Uncaught ReferenceError: exports is not defined
Object.defineProperty(exports, '__esModule', { value: true });

How do I get rollup to work with Deno?

1 Answers

An effort to port rollup to Deno was started in January 2021, so this problem is now solvable. You can import the deno-rollup module and then use it with the same API as rollup.

Here is a version of your original code which runs under Deno:

import { rollup } from "https://deno.land/x/drollup@2.42.3%2B0.17.1/mod.ts";

const bundle = await rollup({
  input: "./index.mjs",
});

const { output } = await bundle.generate({
  format: "esm",
  sourcemap: "inline",
});

for (const chunkOrAsset of output) {
  if (chunkOrAsset.type === "asset") {
    console.log("Asset", chunkOrAsset);
  } else {
    console.log("Chunk", chunkOrAsset.modules);
  }
}

You can find multiple examples of using the deno-rollup port on their repository: https://github.com/cmorten/deno-rollup

Please note that Deno's runtime compilation API is considered an unstable API, which means that you must use the --unstable flag when running Deno in order to make it available. For example: deno run --unstable --allow-read=. build.ts

Related