Split up theme Javascript into multiple files

Complex theme javascript can be split into multiple files, to keep things nicely organised.

To use this functionality, simply add files to the /javascripts folder in your theme directory. These files can not be edited from the Discourse UI, so you must use the Theme CLI or source the theme from git.

Javascript files are treated exactly the same as they are in core/plugins, so you should follow the same file/folder structure. Theme files are loaded after core/plugins, so if the filenames match, the theme version will take precedence.


As an example, you can now accomplish Using Plugin Outlet Connectors from a Theme or Plugin by adding a single file to your theme:

/javascripts/my-theme/connectors/discovery-list-container-top/add-header-message.gjs

import Component from "@glimmer/component"; import { service } from
"@ember/service"; export default class HeaderMessage extends Component {
@service currentUser;

<template>
  Welcome
  {{this.currentUser.username}}
</template>
}

To use the JS API, create an initializer:

/javascripts/discourse/api-initializers/init-theme.gjs

import { apiInitializer } from "discourse/lib/api";

export default apiInitializer((api) => {
  // Your code here
});

If you need a totally different .js asset (e.g. for a web worker), check out this topic.


This document is version controlled - suggest changes on github.

27 Likes