커스텀 테마/플러그인에 npm 패키지 설치 방법

마침 같은 퀘스트에 있는 사람을 찾았네요. 저는 다음과 같이 해결했습니다:

  1. content_security_policy 설정을 끄기
  2. 스크립트를 명시적으로 프로그램 방식으로 추가하기 ($.getScript나 다른 방법을 사용하지 않음).

제가 성공적으로 작동하게 한 예시 요약 스니펫은 다음과 같습니다 (웹 컴포넌트는 상황에 맞게 대체하세요):

import { withPluginApi } from "discourse/lib/plugin-api";

let flag = false;

export default {
  name: "web-component",
  initialize() {
    withPluginApi("0.8", api => {
      api.onAppEvent("page:changed", () => {
        if (flag) return;

        addScript(
          "https://unpkg.com/web-component@0.0.1/dist/web-component/web-component.js",
          { defer: "", crossorigin: "anonymous" }
        );

        addWebComponent(
          "web-component",
          {
            id: "web-component"
          },
          `Hello world`
        );

        flag = true;
      });
    });
  }
};

function addWebComponent(tag, attrs, content) {
  var component = document.createElement(tag);

  Object.keys(attrs).forEach(key => {
    component.setAttribute(key, attrs[key]);
  });
  component.textContent = content;

  document.body.appendChild(component);
}

function addScript(src, attrs) {
  var script = document.createElement("script");

  script.setAttribute("src", src);

  Object.keys(attrs).forEach(key => {
    script.setAttribute(key, attrs[key]);
  });

  document.body.appendChild(script);
}