Serpack
Apis
Serpack/runtime

serpack/runtime

As you can see from the compilation results of serpack, you can see about 5 lines of definitions and other additional code to run.

You can hide this additional code using the runtime.

Terminal
npx serpack ./src/index.ts --runtime

#APIs

#env()

Load runtime environment variables.

Typescript
import { env } from 'serpack/runtime';
 
console.log(env().target === 'node'); // type target = "browser" | "node"

#createRequire() --runtime node-only

Receive a virtual module and create a requirement.

Typescript
import { createRequire } from 'serpack/runtime';
 
// createRequire is node-only feature
process.env.__RUNTIME__ = JSON.stringify({ target: 'node' });
 
const $require = createRequire({
  1: (__serpack_require__, require, module, exports) => {
    module.exports = 'Hello World';
  },
});
 
console.log($require('sp:1')); // Hello World

INFO

The prefix sp: is used to distinguish whether it is a virtual module or a module that is excluded from a bundle, such as node_modules and node: modules

#Size Reduction

Plain
553 KB

Size reduced by 60%.


#Troubleshooting

#Error: Cannot find module '@swc/helpers'

This error occurs because the @swc/helpers package is damaged or missing.

Terminal
npm i --save-dev @swc/helpers

#TypeError: __serpack_require__ is not a function

An error occurred because the target is not set to node. This can occur when you create a require using createRequire().

Typescript
process.env.__RUNTIME__ = JSON.stringify({ target: 'node' });
// or window.__RUNTIME__ = JSON.stringify({ target: 'node' });

Change runtime environment to node.

TIP

createRequire() returns null when not in a node environment