Logo of bundle-runner

bundle-runner

在 Node.js 中运行 webpack 打包,可选择 VM 沙箱

此软件包允许在 Node.js 中运行 Webpack bundle,并可选择沙盒上下文。这对于开发、从内存加载 bundle (HMR) 以及在开发和生产环境之间以一致的方式加载 bundle 非常有用。

✅ 沙盒的作用

  • 可选的沙盒功能,使用 Node.js VM
  • 减轻脚本评估对全局对象的副作用
  • 避免不必要的共享状态
  • 避免 HMR 期间的内存泄漏

❌ 沙盒不适用于

  • 完全避免评估的副作用
  • 用于运行不受信任代码的安全沙盒
  • 高性能

安装

yarn add bundle-runner

npm install bundle-runner

用法

import { createBundle } from 'bundle-runner'

const { evaluateEntry } = createBundle('path/to/bundle.json')

const entry = evaluateEntry(context)

createBundle

function createBundle(bundle: Partial<Bundle> | string, options?: CreateBundleOptions): {
    bundle: Bundle;
    evaluateEntry: (context: object) => any;
    evaluateModule: (filename: string, context: object) => any;
    rewriteErrorTrace: (err: Error) => Promise<Error>;
}

CreateBundleOptions

type CreateBundleOptions = {
    basedir?: string;
    runInNewContext?: 'once' | boolean;
    runningScriptOptions?: VM.RunningScriptOptions;
}

Bundle 格式

输入可以是字符串(指向 .js 文件或包含 bundle 格式的 .json 文件的路径),也可以是直接的 bundle 对象,类型为

type Bundle = {
    basedir: string;
    entry: string;
    files: {
        [filename: string]: string
    };
    maps: {
        [filename: string]: string
    };
}

SourceMap 支持

创建 bundle 后,会暴露一个 rewriteErrorTrace 工具函数,您可以使用它来重写堆栈跟踪

const { evaluateEntry, rewriteErrorTrace } = createBundle('path/to/bundle.json')

try {
  const entry = evaluateEntry(context)
  const app = await entry({})
} catch (err) {
  await rewriteErrorTrace(err)
  throw err
}

致谢

灵感来源于 vue-server-renderer,由 尤雨溪 制作。

许可

MIT