【问题标题】:three.js over cdn using svelte or react使用 svelte 或 react 在 cdn 上的三个.js
【发布时间】:2021-12-08 14:16:43
【问题描述】:

有什么方法可以构建我的苗条或反应应用程序,将three.js 模块(我通常使用npm 导入)将被声明为将从CDN 调用模块的脚本标记?我想保持框架的优势,但也能够减少我最终的包大小,因为我的大部分包都包含三个代码。

感谢你的智慧

【问题讨论】:

  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。

标签: javascript reactjs three.js svelte


【解决方案1】:

有两种方法可以实现减少捆绑包大小的目标:

  1. 从 CDN 导入(您的建议)
  2. 代码拆分

从 CDN 导入

为了保持 ESModules 的语义,您可以简单地将当前的 three.js 导入替换为来自 npm CDN 的 URL,例如 unpkg

Pros Cons
No extra configuration needed Slower to load, as browser needs to spin up new connections to access third-party CDN

异步

<script>
  // App.svelte

  import('https://unpkg.com/three@0.133.1/build/three.min.js').then(({ default: THREE }) => {
    // your code here
  });
</script>

同步

注意:像这样导入会阻止在 three.js 下载时加载脚本的其余部分,这违背了整个 shebang 的目的。它只是为了完整性而在这里

<script>
  // App.svelte

  import { default as THREE } from 'https://unpkg.com/three@0.133.1/build/three.min.js';

  // your code here
</script>

代码拆分

这种方法利用了您已经在使用捆绑器这一事实(可能是rollupvitewebpack)。此答案将重点关注rollup,因为它是svelte 示例中使用的默认值。

Pros Cons
Faster to load, as browser can use existing connections to access first-party resources More complicated to get set up

异步

在您的rollup.config.js 文件中,确保将output.format 设置为'esm' 并且设置output.dir 而不是output.file

// rollup.config.js

import svelte from 'rollup-plugin-svelte';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import postcss from 'rollup-plugin-postcss';

const production = !process.env.ROLLUP_WATCH;

export default {
  input: 'src/index.js',
  output: {
    sourcemap: !production,
    format: 'esm',
    name: 'app',
    dir: 'public',
  },
  plugins: {
    // your plugins

    svelte({
      compilerOptions: {
        dev: !production,
      },
    }),

    postcss({
      extract: 'bundle.css',
    }),

    resolve({
      browser: true,
      dedupe: ['svelte'],
    }),

    commonjs(),
  }
}
<script>
  // App.svelte

  import('three').then(({ default: THREE }) => {
    // your code here
  });
</script>

注意:由于在编译时如何评估代码拆分,因此没有同步方式。另外,那样做也没多大意义。

【讨论】:

    【解决方案2】:

    是的,您可以执行以下操作:

    在您的“index.html”文件中,您可以从 CDN 导入 js 文件,如下所示:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    

    然后,在您想要使用它的文件中,例如可能是一个 React 组件,您可以执行以下操作:

    const THREE = window.THREE;
    

    这将替换您的导入语句,这将是 import * as THREE from "three";import THREE from "three";

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      • 2020-06-10
      • 1970-01-01
      • 2021-10-01
      • 2018-01-28
      • 1970-01-01
      相关资源
      最近更新 更多