serpack/runtime
The output generated by serpack
includes various functions and helper scripts that ensure smooth execution of JavaScript scripts.
However, redeclaring helpers that already exist leads to increased file size and inefficiency.
To address this issue, you can omit the declaration of these helpers.
Instead, a separate runner is required to execute the compiled file.
#Compilation
import { compile } from 'serpack';
compile('src/index.ts', { runtime: true });
#Execution
To run the compiled module, use createRuntime
to create a runtime environment and execute it.
import { createRuntime } from 'serpack/runtime';
const runtime = createRuntime('./output.js');
runtime.execute();
Simply pass the output path of the module compiled with the runtime
option into createRuntime
, and it will handle execution.
#Runtime Instance
#runtime.execute() --runtime
Execute the compiled module and get its exported value.
export default {
apple: '🍎',
};
#runtime.createExternalModule() --runtime
Create virtual module.
import { name } from 'hello'; // module "hello" is a virtual module.
console.log(`Hello ${name}!`); // Hello World!
#runtime.require() --runtime node-only
Same: #createRequire()
#APIs
#env()
Load runtime environment variables.
import { env } from 'serpack/runtime';
console.log(env().target === 'node'); // type target = "browser" | "node"
#createRequire() node-only
Receive a virtual module and create a requirement.
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
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.
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()
.
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