Skip to content

Hello world (Rollup)

Chung Leong edited this page Mar 19, 2024 · 8 revisions

Creating project

mkdir hello
cd hello
npm init -y
npm install --save-dev rollup rollup-plugin-zigar @rollup/plugin-node-resolve 
mkdir zig
const std = @import("std");

pub fn hello() void {
    std.debug.print("Hello world!", .{});
}
import nodeResolve from '@rollup/plugin-node-resolve';
import zigar from 'rollup-plugin-zigar';

const input = './zig/hello.zig';

export default [
  {
    input,
    plugins: [
      zigar({ optimize: 'ReleaseSmall' }),
      nodeResolve(),
    ],
    output: {
      file: './dist/index.js',
      format: 'esm',
    },
  },
];
Welcome to Node.js v20.10.0.
Type ".help" for more information.
> const { hello } = await import('./dist/index.js');
Uncaught TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11730:11)
    at async WebAssemblyEnvironment.instantiateWebAssembly (file:///.../hello/dist/index.js:2414:22)
    at async file:///.../hello/dist/index.js:2421:28 {
  cause: Error: not implemented... yet...```
  Zigar({ 
    optimize: 'ReleaseSmall', 
    useReadFile: true,  // <---
  }),
  Zigar({ 
    optimize: 'ReleaseSmall', 
    embedWASM: true,  // <---
  }),
Welcome to Node.js v20.10.0.
Type ".help" for more information.
> const { hello } = await import('./dist/index.js');
undefined
> hello();
Hello world!
undefined
> 

Creating CommonJS library

    input,
    plugins: [
      zigar({ 
        optimize: 'ReleaseSmall', 
        embedWASM: true, 
        topLevelAwait: false,  // <---
      }),
      nodeResolve(),
    ],
    output: {
      file: './dist/index.cjs',
      format: 'cjs',  // <---
    },
Welcome to Node.js v20.10.0.
Type ".help" for more information.
> const { hello } = require('./dist/index.cjs');
undefined
> hello();
Hello world!
undefined
Welcome to Node.js v20.10.0.
Type ".help" for more information.
> const { hello } = require('./dist/index.cjs'); hello();
Promise {
  <pending>,
  [Symbol(async_id_symbol)]: 290,
  [Symbol(trigger_async_id_symbol)]: 288
}
> Hello world!
Welcome to Node.js v20.10.0.
Type ".help" for more information.
> const { hello } = require('./dist/index.cjs'); await hello();
Hello world!
undefined
Welcome to Node.js v20.10.0.
Type ".help" for more information.
> const { hello, __zigar } = require('./dist/index.cjs'); await __zigar.init(); hello();
Hello world!
undefined

Creating UMD library

    input,
    plugins: [
      zigar({ 
        optimize: 'ReleaseSmall', 
        embedWASM: true, 
        topLevelAwait: false,
      }),
      nodeResolve(),
    ],
    output: {
      file: './dist/index.umd.cjs',
      format: 'umd',  // <---
      name: 'Hello',  // <---
    },
<!DOCTYPE html>
<html> 
  <head>
    <script src="dist/index.umd.cjs"></script>
    <script>
      window.onclick = () => Hello.hello();
    </script>
  </head>
  <body>
    <h1>Click me!</h1>
  </body>
</html>
Clone this wiki locally