如何为用svelte.js编写的应用程序创建插件?

时间:2019-12-10 12:09:28

标签: javascript plugins svelte svelte-3

如果我是用纯JS编写应用程序,则将建立这样的插件连接:

  

App.js

var App = function(){ /* ... */ };
//...
App.prototype.regPlugin= function ( atr1, atr2, ... ) { /* ... */ };
//...
App.prototype.sendToEventBus = function ( atr1, ... ) { /* ... */ };
//...
var app = new App();
//...
var appModules = {};
//...
document.onreadystatechange = function () {
   if ( document.readyState === 'complete' ){
      for ( var module in AppModules ) {
        if ( AppModules[ module ] ) {
        try {
            AppModules[ module ].init( app );
        } catch(er) {
            //...
        }
      }
   }
}
//...
  

plugin.js

var MyPlugin = function (){ /*...*/ };
//...
MyPlugin.prototype.init = function ( app ) {
    this.app = app;
    //...
    app.regPlugin( plugAtr0 );
    //...
};
//...
MyPlugin.prototype.handleAny = function(){
   this.app.sendToEventBus( /* my event */ );
};
//...
appModules.myPlugin = new MyPlugin();

如何类似地在svelte.js上为应用程序制作插件?
自定义元素不太适合此操作。

2 个答案:

答案 0 :(得分:2)

好吧,如果您愿意的话,可以做一些非常相似的事情。 Svelte只为您提供一个UI组件,您可以在页面上的任何位置呈现该组件。它不会接管整个JS。

一件事是,您的Svelte应用程序很可能将使用ES import语句进行捆绑(Rollup或Webpack)。这意味着您的代码将驻留在ES模块中,并且局部变量不会自动附加到ES模块中的window对象。因此,您必须明确说明这一点。因此您的代码将变成这样:

  

App.js (大概是您的应用程序入口点)

import App from './App.svelte'

const app = new App({
  target: document.body,
  props: {
    name: 'world',
  },
})

const appModules = {}

// expose appModules as a global variable
window.appModules = appModules

document.onreadystatechange = function() {
  if (document.readyState === 'complete') {
    debugger
    for (var module in appModules) {
      if (appModules[module]) {
        try {
          appModules[module].init(app)
        } catch (er) {
          //...
        }
      }
    }
  }
}

因此,app是您的Svelte根组件。它将保存在App.svelte文件中。 Svelte允许您通过exporting const or function向组件添加实例方法。

  

App.svelte

您可以导出constfunction以在Svelte组件上具有实例方法。

<script>

  export function regPlugin(...) { ... }

  // or
  export const sentToEventBus(...) { ... }

</script>
...

然后...Voilà?您的代码中还有其他内容吗?

上面的代码可能存在的一个问题是App组件将在您的插件有机会注册之前呈现。

您可以在App组件中使用道具来解决此问题。为了能够从“控制器代码”中更改此prop的值,可以使用组件的$set方法。您也可以在组件上设置accessors选项。您可以使用捆绑程序插件选项在全局上执行此操作,也可以使用<svelte:options>在单个组件上启用它。

如果您需要一些仅在应用就绪后才能运行的自定义逻辑,则可以在"reactive statement"中进行。

  

App.svelte

<svelte:options accessors={true} />

<script>
  export function regPlugin() {}
  export function sentToEventBus() {}

  export let ready = false

  $: if (ready) {
    // code to run when ready
  }
</script>

{#if ready}
  <!-- content to show when ready (all plugins initialized) -->
  <!-- most likely, you'd put other Svelte components in there -->
{:else}
  <div>Loading...</div>
{/if}

您可以在应用准备启动时切换此道具:

  

App.js

document.onreadystatechange = function() {
  if (document.readyState === 'complete') {
    for (var module in appModules) {
      ...
    }

    app.$set({ ready: true })
    // or
    app.ready = true
  }
}

或者,您可能希望在App组件中移动插件初始化代码。由于这里有一个“静态”状态,因此在appModules变量中,您必须将其放入组件的静态<script context="module">部分:

  

App.svelte

<script context="module">
  // this block only runs once, when the module is loaded (same as 
  // if it was code in the root of a .js file)

  // this variable will be visible in all App instances
  const appModules = {}

  // make the appModules variable visible to the plugins
  window.appModules = appModules

  // you can also have static function here
  export function registerPlugin(name, plugin) {
    appModules[name] = plugin
  }
</script>

<script>
  // in contrast, this block will be run for each new instance of App

  ...

  let ready

  document.onreadystatechange = function() {
    if (document.readyState === 'complete') {
      // NOTE appModules bellow is the same as the one above
      for (var module in appModules) {
        // ...
      }
      ready = true
    }
  }
</script>

{#if ready}
  ...
{/if}

静态函数addPlugin可以作为命名输出从其他模块访问:

import { addPlugin } from './App.svelte'

这可能更适合于捆绑有模块的应用程序/带有模块的应用程序,而不是将内容附加到window(因此在全局名称空间中存在冲突的风险)。取决于你在做什么...

答案 1 :(得分:1)

那种类型的插件设置仍然可以使用,请查看Client-side component API

使用component.$set,您可以将道具从插件更改为苗条的组件。

从svelte内部向插件/应用程序添加侦听器时,您可能需要附加分配data = myPlugin.data才能使svelte能够对更改做出反应。