有两种方法可以实现减少捆绑包大小的目标:
- 从 CDN 导入(您的建议)
- 代码拆分
从 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>
代码拆分
这种方法利用了您已经在使用捆绑器这一事实(可能是rollup、vite 或webpack)。此答案将重点关注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>
注意:由于在编译时如何评估代码拆分,因此没有同步方式。另外,那样做也没多大意义。