<script content=”module”>

具有context =“module”属性的<script>的模块在首次解析时运行一次,而不是每个组件实例都运行一次。在此类型的模块中申明的Values可以被普通的<script>标签访问到(包括组件标签)但是相反则无法这么使用。 你可以从此模块中export这些绑定值,并且他们会成为编译过的模块的导出值 你无法export默认值,因为默认导出的是组件本身。

  1. <script context="module">
  2. let totalComponents = 0;
  3. // this allows an importer to do e.g.
  4. // `import Example, { alertTotal } from './Example.svelte'`
  5. export function alertTotal() {
  6. alert(totalComponents);
  7. }
  8. </script>
  9. <script>
  10. totalComponents += 1;
  11. console.log(`total number of times this component has been created: ${totalComponents}`);
  12. </script>