---
title: Plugins and components
project: Total.js V5
version: 0.0.20
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/guides/plugins-and-components/
updated: 2026-11-16T16:36:21.082Z
---

# Plugins and components

> Plugins in the plugins/ folder, PLUGINS, UI bundles from COMPONENTATOR(), server components with NEWCOMPONENT(), and NPMINSTALL(), REQUIRE() and IMPORT().

A **plugin** is a folder in `plugins/` that packs one feature of the application: its own controllers, actions, schemas, public files and views. Total.js loads every plugin at start, together with the files of the application, so a plugin works like a small application inside the main one.

This page also covers **components**: UI component bundles downloaded from Componentator with `COMPONENTATOR()`, server components compiled with `NEWCOMPONENT()`, and the helpers that load code at run time: `NPMINSTALL()`, `REQUIRE()` and `IMPORT()`. The full list of methods is in the reference [Plugins and components](../../reference/plugins-and-components/).

## Structure of a plugin

```text
plugins/
	shop/
		index.js          <- required: the plugin definition
		controllers/      <- routes of the plugin
		actions/
		schemas/
		models/
		definitions/
		extensions/
		middleware/
		public/           <- static files, served as /_shop/...
		views/            <- views, rendered as #shop/views/...
```

The name of the folder is the **id** of the plugin. A folder without an `index.js` file is skipped, together with all its subfolders. Folders whose name contains `-bk` or `_bk` are skipped too, so you can switch a plugin off by renaming `shop` to `shop-bk`.

## index.js

`index.js` is an ordinary Node.js module. Total.js requires it, stores it in `PLUGINS` under the id of the plugin and calls its `install()` function.

```js
// plugins/shop/index.js
exports.icon = 'ti ti-shopping-cart';
exports.name = 'Shop';
exports.position = 3;
exports.permissions = [{ id: 'shop', name: 'Shop' }, { id: 'shop_orders', name: 'Orders' }];
exports.visible = user => user.sa || user.permissions.includes('shop');

exports.install = function() {
	ROUTE('+API    ?    shop_orders    --> Shop/orders');
	ON('ready', function() {
		// the whole application is loaded
	});
};
```

The framework itself reads only these properties:

| Property | What Total.js does with it |
| --- | --- |
| `exports.install` | Called once, when the plugin is loaded |
| `exports.id` | Set to the folder name when you do not define it |
| `exports.name` | Written with the id and the permissions to the source map of the application (debug mode) |
| `exports.permissions` | An array of strings or objects with `id`; the ids are written to the source map |

Any other property, such as `icon`, `position` or `visible`, is yours: your administration UI reads it from `PLUGINS` to build a menu or to hide items the user may not open.

## Files inside a plugin

These subfolders of a plugin are loaded exactly like the folders of the same name in the root of the application: every `.js` file is required and its `install()` is called.

| Folder | Content |
| --- | --- |
| `controllers/` | Routes, see [Routing](../routing/) |
| `actions/` | `NEWACTION()` definitions, see [Actions](../actions/) |
| `schemas/` | Schemas and actions, see [JSON schemas](../json-schemas/) |
| `models/`, `definitions/`, `extensions/` | Shared code, delegates, prototypes |
| `middleware/` | `NEWMIDDLEWARE()` definitions, see [Middleware](../middleware/) |

All plugins and all application files share one global space: a route, an action or a schema declared in a plugin is available everywhere. Use the plugin id as a prefix of names (`Shop/orders`, `/admin/shop/`) to avoid conflicts.

```js
// plugins/shop/controllers/api.js
exports.install = function() {
	ROUTE('+API    ?    shop_products    --> Shop/products');
	ROUTE('+GET    /admin/shop/', function($) {
		$.view('#shop/views/index');
	});
};
```

## Public files, views and templates

- **Public files**: a URL that starts with `/_` and the plugin id is served from the `public/` folder of the plugin. `/_shop/css/shop.css` reads `plugins/shop/public/css/shop.css` (see [Static files](../static-files/)).
- **Views**: a view name that starts with `#` is relative to the `plugins/` folder: `$.view('#shop/views/index')` renders `plugins/shop/views/index.html` (see [Views](../views/)).
- **Templates**: `TEMPLATE('#shop/templates/order.html', model)` reads `plugins/shop/templates/order.html`. `.html` is added when the name does not contain it.
- **Paths**: `PATH.plugins('shop/data.json')` returns the absolute path of a file in the plugins folder.

In debug mode the `plugins/` folder is watched like `controllers/`: a change of a script restarts the application.

## Configuration of a plugin

A plugin can have a `config` file next to its `index.js`. It has the same format as the main `config` file (see [Configuration](../configuration/)) and is read before the scripts of the application and the plugins run, after the main `config`. Its keys are merged into `CONF`, so a plugin can bring its own defaults, and a key with the same name overrides the value from the main file.

```text
// plugins/shop/config
shop_currency    : EUR
shop_pagesize    : 20
```

```js
// plugins/shop/actions/products.js
NEWACTION('Shop/products', {
	action: function($) {
		var take = CONF.shop_pagesize;
		// ...
		$.success();
	}
});
```

## FlowStream in a plugin

When a plugin contains an `index.flow` file (a FlowStream export in JSON), Total.js reads it and starts the FlowStream right after the `index.js` of the plugin, before the other files of the plugin; the FlowStream is created asynchronously, so `PLUGINS[id].flowstream` is set once it is ready. The FlowStream gets the plugin id as its id, the plugin `name` (translated) as its name and the plugin folder as its directory. The running instance is stored in `PLUGINS[id].flowstream`. See [FlowStream](../flowstream/).

```js
// plugins/iot/index.js
exports.name = 'IoT';
exports.install = function() {
	ON('ready', function() {
		setTimeout(function() {
			var flow = PLUGINS.iot.flowstream;
			flow && console.log('IoT FlowStream is running');
		}, 1000);
	});
};
```

## PLUGINS

`PLUGINS` is an object with all loaded plugins, by id. Each value is the `module.exports` object of the plugin `index.js`.

```js
// a menu for an admin panel
ROUTE('+GET /admin/plugins/', function($) {
	var user = $.user;
	var arr = [];
	for (var id in PLUGINS) {
		var plugin = PLUGINS[id];
		if (plugin.visible && !plugin.visible(user))
			continue;
		arr.push({ id: id, name: plugin.name, icon: plugin.icon, position: plugin.position });
	}
	arr.quicksort('position');
	$.json(arr);
});
```

## UI components (COMPONENTATOR)

`COMPONENTATOR(name, components, [removeprev], [attrs])` downloads one minified bundle of jComponent UI components from `https://componentator.com` into `public/`. The file is downloaded only when it does not exist yet, so call it in a definition file and keep it in the code.

```js
// definitions/ui.js
COMPONENTATOR('ui', 'exec,locale,aselected,page,viewbox,input,box,validate,loading,notify,message,errorhandler,empty,menu,colorpicker,icons,directory,miniform,preview,datagrid', true);
```

The bundle is saved as `public/ui-<name>-<hash>.min.js` (`public/ui-<hash>.min.js` when `removeprev` is `false`); the hash comes from the list of components, so a different list gives a new file and (with `removeprev`, the default) the old bundle of the same name is deleted. The URL of the file is stored in `REPO[name]`, so a layout can load it:

```html
<script src="@{REPO.ui}"></script>
```

## Server components (NEWCOMPONENT)

A server component is an HTML file with a `<script total>` (or `<script node>`) block that holds the server code, optionally with `<settings>`, `<style>`, `<script>`, `<body>`, `<readme>`, `<schema>` and `<template>` parts for a UI. `NEWCOMPONENT()` compiles it into a component object; you create instances of it and send them data.

```html
<!-- components/uppercase.html -->
<script total>

	exports.name = 'Uppercase';
	exports.config = { prefix: '' };
	exports.inputs = [{ id: 'input', name: 'Text' }];
	exports.outputs = [{ id: 'output', name: 'Result' }];

	exports.make = function(instance, config) {
		instance.message = function(msg) {
			msg.send('output', config.prefix + String(msg.data).toUpperCase());
		};
	};

</script>
<readme>
Converts the text to upper case.
</readme>
```

```js
var com = await NEWCOMPONENT('uppercase');   // reads components/uppercase.html
com.debugger = false;                       // do not print outputs to the console

var instance = com.create({ prefix: '> ' });
instance.input('input', 'hello', function(msg) {
	console.log(msg.output, msg.data);      // output > HELLO
});
```

`NEWCOMPONENT()` accepts the name of a file in `components/`, the HTML itself, or an `https://` URL. Packages listed in `exports.npm` are installed with `NPMINSTALL()` before `exports.install()` runs. An instance can also emit data on its own with `instance.send(output, data)`, for example from a timer, and report progress with `instance.activity(key, name, value)`. An input with a `schema` (a schema string such as `'name:String, age:Number'`) validates the data: the cleaned data is in `msg.data` and errors in `msg.error`.

## NPM packages and remote modules

- `NPMINSTALL(name, [callback])` installs an NPM package into `CONF.$nodemodules` (the `node_modules` folder of the application) with `npm install`. It does nothing when the package is already there (and has the version from `name@version`).
- `REQUIRE(name)` loads a module: Node.js built-in modules directly, other packages with `require()` and, when that fails, from `CONF.$nodemodules`.
- `IMPORT(url, [callback])` downloads a JavaScript file into the temporary folder and requires it. A second call with the same URL in the same process returns the loaded module without downloading. An error page (status `400` or more) or a file that is not a module gives an error.

```js
// plugins/pdf/index.js
exports.install = async function() {
	await NPMINSTALL('pdfkit@0.15.0');
	var PDFDocument = REQUIRE('pdfkit');
	// ...
};
```

```js
IMPORT('https://cdn.example.com/helpers.js', function(err, module) {
	if (!err)
		module.hello();
});
```
