有沒有辦法以某種方式構建我的 svelte 或 react 應用程式,將 Three.js 模塊(我通常使用 npm 匯入)宣告為腳本標簽,它將從 CDN 呼叫模塊?我想保留框架的優勢,但也能夠減少我的最終包大小,因為我的大部分包包含三個代碼。
謝謝你的智慧
uj5u.com熱心網友回復:
是的,您可以執行以下操作:
在您的“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";
uj5u.com熱心網友回復:
有兩種方法可以實作減少包大小的目標:
- 從 CDN 匯入(您的建議)
- 代碼拆分
從 CDN 匯入
為了保持 ESModules 的語意,你可以簡單地用three.js來自 npm CDN 的 URL替換當前的匯入,例如unpkg:
| 優點 | 缺點 |
|---|---|
| 無需額外配置 | 加載速度較慢,因為瀏覽器需要啟動新連接才能訪問第三方 CDN |
異步
<script>
// App.svelte
import('https://unpkg.com/[email protected]/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/[email protected]/build/three.min.js';
// your code here
</script>
代碼拆分
此方法需要的,你已經在使用捆綁的事實(可能是優勢rollup,vite或webpack)。此答案將重點關注,rollup因為它是svelte的示例中使用的默認值。
| 優點 | 缺點 |
|---|---|
| 加載速度更快,因為瀏覽器可以使用現有連接訪問第一方資源 | 設定起來比較復雜 |
異步
在您的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>
Note: There is no synchronous way due to how code-splitting is evaluated at compile time. Plus it doesn't make much sense to do it like that anyways.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/330759.html
標籤:javascript 反应 三.js 苗条的
上一篇:如何在reactjs中檢查以帶有Routehook的短語開頭的隨機生成的url
下一篇:歐元的貨幣格式
