将主题 Javascript 分割成多个文件

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 个赞

假设我不知道 core/plugins 的文件层级结构,因为我只是来创建一个新的主题组件。我应该在哪里查找信息?目录和其中的文件的命名约定是什么?

仅仅查看各种主题/组件,会发现各种不同的嵌套方案和子目录。我一直没能找出规律,也找不到任何文档。(例如,/initializers/api-initializers/pre-initializers 之间有什么区别? :crying_cat_face:

1 个赞

这里的文件使用API。老实说,我也疑惑了很久,为什么我不能把 api-initializers 文件放在 initializers 里?

是的。这很难理解。我宁愿不去想我花了 3 个小时做某件事,结果却发现我给某样东西命名错误或放错了位置,或者有时,忘记以看似有许多方法中的一种来包含它(在 plugin.rb 中,在 js 文件中的 include 中——什么路径?我需要扩展名吗?)

最好的方法是使用 安装 Discourse 主题 CLI 控制台应用程序来帮助您构建主题,并让它为您创建一个主题骨架。它还使调试变得非常容易,因为它会自动将其上传到您的服务器(一个普通的生产服务器),并且(通常)会自动重新加载您的浏览器。

不知道有什么区别,或者是否有区别(我认为没有?但我不太清楚)。我会使用主题骨架中的那个。

有一个名为 all-the-themes 的仓库。您可以获取它并搜索其中的示例。并且始终使用最近更改过的那个。

3 个赞

EmberJS(以及 Rails)在很大程度上依赖于约定。大多数时候这都很棒,但当你犯了哪怕是很小的错误时,例如命名,它也会变得_极其_令人沮丧。

3 个赞

FWIW,我在这里找到了对 api-initializers/ 的解释:

(然后它连接到 Ember 文档,然后就开始有意义了。)

仍然希望有一个文档能对目录结构的可能性进行基本的枚举/解释。(例如,我知道 connectors/ 是一个东西……还有更多吗?)

另外,FWIW:主题 CLI 应用程序从以下位置拉取骨架:

它只提到了 api-initializers/

(事实上,我正在使用主题 CLI 应用程序,但在我开始制作主题组件后才开始使用它,所以我跳过了骨架步骤。)

2 个赞