Babel Preset njs

raw JSON →
0.7.0 verified Sat Apr 25 auth: no javascript

A Babel preset for transforming modern JavaScript (up to ES2021) into code compatible with njs (NGINX JavaScript). Current stable version is 0.7.0, targeting njs ≥ 0.7.0, with peer dependency on @babel/core ^7.0.0-0. Key differentiator: provides a curated set of Babel plugins for features not yet supported by njs (e.g., classes, for-of, object rest/spread), while skipping transformations for features njs already supports (e.g., arrow functions, block scoping, destructuring). Ideal for developers writing njs scripts with modern JS syntax.

error ReferenceError: require is not defined in ES module scope
cause Using require() to load the preset in an ES module environment.
fix
Use import babelPresetNjs from 'babel-preset-njs' or use require in a CommonJS context.
error SyntaxError: Unexpected token '.' (when using optional chaining)
cause Optional chaining (?.) is not yet supported by njs and not included in the preset's plugins.
fix
Avoid optional chaining; use if statements or add @babel/plugin-proposal-optional-chaining manually.
error Error: Plugin/Preset files are not allowed to export objects, only functions
cause Using an older version of the preset that exports an object instead of a function.
fix
Update to babel-preset-njs@0.7.0 and ensure @babel/core is version 7+.
breaking Version 0.7.0 requires njs ≥ 0.7.0. Older versions of njs may not work.
fix Upgrade njs to at least 0.7.0 or use an older version of the preset (0.2.1 max).
gotcha The preset does NOT transform dynamic import() or generators (yield) as njs does not support them. These will fail at runtime.
fix Avoid using dynamic imports and generators in njs code, or provide your own custom plugin.
deprecated Some plugins included may become unnecessary as njs evolves. Check compatibility table before upgrading.
fix Review the plugin list in the preset's README to see which features are now natively supported.
npm install babel-preset-njs
yarn add babel-preset-njs
pnpm add babel-preset-njs

Shows installation, Babel config, and a simple njs script using for-of and object spread, both of which are transformed by the preset.

// Install: npm install --save-dev @babel/core babel-preset-njs
// Then create babel.config.js:
module.exports = {
  presets: ['babel-preset-njs']
};

// Now write your njs script (src/index.js):
const arr = [1, 2, 3];
const obj = { a: 1, b: 2 };
const spread = { ...obj, c: 3 };
for (const x of arr) {
  ngx.log(ngx.INFO, x);
}

// Run: npx babel src/index.js --out-dir dist
// Result will be compatible with njs (e.g., for-of transpiled, object spread transformed).