Skip to content

Latest commit

 

History

History
254 lines (181 loc) · 10.5 KB

module-system_us.md

File metadata and controls

254 lines (181 loc) · 10.5 KB

English · 中文

Module system

Once your scripts grow, you will want to split them into several files. This page shows how to share code between files with import / export or require, how to use npm packages, and how to import Java classes directly.

Split code into several files

ES modules (import / export) are the recommended style. For example, move constants and helpers into a lib/ folder:

nekojs/server_scripts/
├── lib/
│   ├── constants.js
│   └── recipe_helpers.js
└── main.js
// lib/constants.js
export const ORES = ['minecraft:iron_ore', 'minecraft:gold_ore']
// lib/recipe_helpers.js
export function smeltOre(event, ore, output) {
  event.smelting(Item.of(output), Ingredient.of(ore)).id(`nekojs:smelt_${ore.split(':')[1]}`)
}
import { ServerEvents } from "nekojs:event/versioned";

// main.js
import { ORES } from './lib/constants.js'
import { smeltOre } from './lib/recipe_helpers.js'

ServerEvents.recipes(event => {
  for (const ore of ORES) {
    smeltOre(event, ore, ore.replace('_ore', '_ingot'))
  }
})

Run /nekojs reload. A furnace now smelts iron ore and gold ore straight into ingots.

Keep these points in mind:

  • Relative paths (./, ../) start from the folder of the current file.
  • Write the full file name, including the extension, for example ./lib/constants.js.
  • Every file in a script folder is loaded as a script, including files in lib/. Helper files should only export functions and constants. Do not register events or do one-time work at their top level.

Default exports, import * as ns, circular imports, import.meta, top-level await and dynamic import() also work. You can import JSON files too:

import settings from './settings.json'
console.info(settings.enabled)

CommonJS

You can also use require and module.exports:

// utils.cjs
function calculateDamage(base, multiplier) {
  return base * multiplier
}
module.exports = { calculateDamage }
// main.cjs
const { calculateDamage } = require('./utils.cjs')
console.info(calculateDamage(4, 1.5)) // 6

The two styles mix: import can load a .cjs file, and require can load an ES module.

The file extension picks the module type

Extension Runs as
.mjs ES module
.cjs CommonJS
.js Detected: an ES module if the file uses import / export, otherwise CommonJS
.ts / .jsx / .tsx Compiled to JavaScript first, then detected like .js

When in doubt, use .js. Writing export in a .cjs file is a syntax error.

enableEsmAuthoring in nekojs/config/engine.toml defaults to true. If you set it to false, every file runs as CommonJS and import / export become errors; they are not converted for you. You normally do not need to change it.

For TypeScript and JSX, see TypeScript and JSX.

Use npm packages

Put a pure-JavaScript package in nekojs/node_modules/ and refer to it by name:

// nekojs/node_modules/greeting/index.js
module.exports = name => `Hello, ${name}!`
// nekojs/server_scripts/use_greeting.js
const greet = require('greeting')
console.info(greet('NekoJS')) // Hello, NekoJS!

NekoJS looks for greeting in this order:

  1. the file node_modules/greeting itself;
  2. that name plus an extension, such as node_modules/greeting.js;
  3. an index file in that folder, such as node_modules/greeting/index.js.

npm package limits

  • The main and exports fields of package.json are not read. If the entry is not index.js, give the full path, for example require('some-lib/dist/some-lib.js').
  • Packages with native code do not work, for example sharp, better-sqlite3 or canvas.
  • NekoJS provides only some Node.js core modules; see Node.js compatibility. A package that needs other Node APIs will not run.
  • Package code has the same limits as your scripts. It can only access files inside the game folder.

The quickest way to find out whether a package works is to drop it in and try it.

Built-in API modules

Ordinary Bindings such as Item keep their existing global access and official module paths. Java plugin/native Event Groups use custom engine virtual modules with a separate nekojs:event/ namespace. That namespace has exactly two categories, stable and versioned; an optional owner is the final path segment. It does not change Binding routes or global Binding behavior.

Module Contents
nekojs/api/stable Stable APIs such as ID and Native; client scripts also get I18n
nekojs/api/version Current-node Bindings such as Item; no event groups
nekojs:event/stable Portable event views; SERVER-only ServerEvents.tickPre / tickPost
nekojs:event/versioned Explicitly published official native/current-node event groups
import { ID } from 'nekojs/api/stable'
import { Item } from 'nekojs/api/version'
import { ServerEvents } from 'nekojs:event/versioned'

const id = ID.resource('minecraft:stone')
const stack = Item.of('minecraft:stone')
const { ID } = require('nekojs/api/stable')
const { ServerEvents } = require('nekojs:event/versioned')

You do not install these modules. Importing a name that the current script type does not have is an error. For example, ServerEvents in nekojs:event/stable exists only in server scripts and has just two events, tickPre and tickPost.

Plugin Binding modules continue to use nekojs/plugins/<owner>/api/stable and nekojs/plugins/<owner>/api/version (versioned() still selects version). Event groups use the custom engine virtual modules nekojs:event/stable and nekojs:event/versioned; plugin events append the owner, for example nekojs:event/stable/myaddon or nekojs:event/versioned/myaddon. These are the only two event categories, with no server/player submodules. The former event routes have no aliases. Event groups have no automatic globals or Binding aggregate aliases. For native payload semantics migrate to versioned, not automatically to stable. See the event API migration table. Script-created dynamic groups remain global; import their ScriptEvents registrar from nekojs:event/versioned.

The code completion generated by /nekojs probe shows which names you can import right now. For the full list of globals, see Global bindings.

Import Java classes

Use the java: prefix with a slash-separated path to import a Java package or class.

Import a package, then take classes from it:

import { ArrayList } from 'java:java/util'

const list = new ArrayList()
list.add('hello')
console.info(list.size()) // 1

When a class name clashes with a built-in JavaScript name (such as Math), add a $ in front:

import { $Math, Integer } from 'java:java/lang'
console.info($Math.max(3, 7))   // 7
console.info(Integer.MAX_VALUE) // 2147483647

Import a single class; the default export is the class itself:

import ArrayList from 'java:java/util/ArrayList'
const HashMap = require('java:java/util/HashMap')

Path rules:

Rule Example
Must start with java: java:java/util
Use slashes, not dots Write java:java/util/ArrayList, not java:java.util.ArrayList
No . or .. segments java:../foo is an error

You can also skip modules and write Java.type('java.util.ArrayList').

Prefer a NekoJS binding when one exists. For example, use Item.of(...) instead of importing Minecraft's item classes. Bindings are shorter, have code completion and hold up better across Minecraft versions. Keep java: imports for things the bindings do not cover yet.

Top-level await and dynamic import

An ES module can use await at the top level, and it can load a file only when needed:

const config = { enableExtras: true }

if (config.enableExtras) {
  const extras = await import('./lib/extras.js')
  extras.setup()
}

An ES module that uses top-level await cannot be loaded with require. You get Cannot require async ESM module with top-level await: ... Use import() instead. Switch to import() as the message says.

What happens to modules on reload

  • Saving a file does not apply it. Run /nekojs reload (or the reload command for that script type).
  • A reload runs every module again, so module variables start from their initial values.
  • To keep data across reloads, use global; see Script basics. Do not store objects exported by an old module. They are stale after a reload.
  • When you reload a single file (for example /nekojs reload server main.js), changed modules that it imports are reloaded too.

Security limits

Scripts cannot use Java and files freely:

  • Dangerous Java classes cannot be imported, for example java.lang.Runtime, java.lang.Process, java.lang.System, java.io, java.nio, java.net, reflection and class loaders. Both java: and Java.type refuse them.
  • Scripts can only access files inside the game folder, and by default can only write inside nekojs/. See Node.js compatibility.
  • Creating threads, reflection and bytecode manipulation are off by default. The switches are allowThreads, allowReflection and allowAsm in nekojs/config/engine.toml; see Configuration.

These limits stop common mistakes, but they do not make an untrusted script safe. For example, objects returned by Java methods are not checked against the class filter, and NekoJS does not stop an endless loop. Only run scripts and npm packages that you trust.

Next steps


Previous: Registering new content · Contents · Next: TypeScript and JSX