Skip to content

Latest commit

 

History

History
180 lines (135 loc) · 3.45 KB

README.md

File metadata and controls

180 lines (135 loc) · 3.45 KB

VM Worker

npm bundle size npm downloads license

github build coverage

Tiny virtual machine for browser to execute javascript modules in Web Worker.

Features

  • Run code in a isolated scope without pollute your environment
  • Support CommonJS and ESModules (by plugin)
  • Support TypeScript and Flow (by plugin)
  • Based on Web Worker

Usage

Basic usage

App.js

import VM from 'vm-worker'

const vm = VM({
  debug: false, // default false
  timeout: 100000, // default 100000ms
})

await vm.require([
  {
    path: 'module-one/index.js',
    src: 'module.exports = 1',
  },
  {
    path: '/dirA/a.js',
    url: 'https://xxx.com/a.js',
  },
  {
    path: '/dirB/b.js',
    src: 'module.exports = require("../dirA/a")',
  },
])

await vm.exec('/dirB/b.js', 1, 2) // => 4

vm.terminate()

a.js

module.exports = (a, b) => (a + b + require('module-one'))

ESModule Plugin

App.js

import VM from 'vm-worker'
import ESMPlugin from 'vm-worker/dist/plugins/esmodule.esm'

const vm = VM({
  plugins: [
    ESMPlugin(),
  ],
})

await vm.require([
  {
    path: 'module-one/index.js',
    src: `export const ONE = 1`
  },
  {
    path: '/dirA/a.js',
    url: 'https://xxx.com/a.js',
  },
  {
    path: '/dirB/b.js',
    src: `import { plus } from "../dirA/a"
          export default plus`,
  },
])

await vm.exec('/dirB/b.js', 1, 2) // => 4

vm.terminate()

a.js

import { ONE } from 'module-one'

export function plus(a, b) {
  return a + b + ONE
}

Sucrase plugin

Sucrase is similar to Babel, which compiles TypeScript, Flow and JSX to standard JavaScript.

Sucrase transform options document

App.js

import VM from 'vm-worker'
import SucrasePlugin from 'vm-worker/dist/plugins/sucrase.esm'

const vm = VM({
  plugins: [
    SucrasePlugin({
      ... // Sucrase transform options
    }),
  ],
})

await vm.require([
  {
    path: 'module-one/index.js',
    src: `export const ONE: number = 1`
  },
  {
    path: '/dirA/a.js',
    url: 'https://xxx.com/a.js',
  },
  {
    path: '/dirB/b.js',
    src: `import { plus } from "../dirA/a"
          export default plus`,
  },
])

await vm.exec('/dirB/b.js', 1, 2) // => 4

vm.terminate()

a.js

import { ONE } from 'module-one'

export function plus(a: number, b: number) {
  return a + b + ONE
}

Installation

npm i vm-worker