[英]three.js ES6 how import only specific modules
我已經通過NPM安裝了three.js庫,以便利用新的ES6模塊化架構,它可以讓你只導入你需要的模塊,如下所述: Threejs - 通過模塊導入 。
我使用一飲而盡 , browserify和巴貝爾捆綁和transpiling,就像這樣:
gulp.task("build_js", () => {
return browserify({
entries: "./public/app/app.js",
cache: {},
dev: true
})
.transform(babelify, {presets: ["env"], plugins: ["syntax-async-functions", "transform-async-to-generator"], sourceMaps: true})
.bundle()
.pipe(source("app.bundle.min.js"))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: mode}))
.pipe(uglify())
.pipe(sourcemaps.write("./"))
.pipe(gulp.dest(config.build.js))
});
我只想導入我需要的模塊並保持較小的bundle大小,但我注意到browserify生成的bundle具有相同的大小,無論我是導入所有模塊還是只導入一個。
如果在app.js中我導入了所有模塊,我的捆綁大小約為500Kb:
// app.js
import * as THREE from 'three'; // about 500 Kb size
但是如果我嘗試使用ES6語法只導入一個特定的模塊,我得到了相同的包大小(它再次導入所有模塊):
// app.js
import { Vector3 } from 'three'; // about 500 Kb size, same as before example
我也嘗試過以下方法:
// app.js
import { Vector3 } from "three/build/three.module.js";
但是我收到以下錯誤:
SyntaxError: 'import' and 'export' may only appear at the top level (45590:0) while parsing /Users/revy/proj001/node_modules/three/build/three.module.js
我的問題:我怎樣才能正確導入我需要的模塊並保持捆綁尺寸小?
你錯過了Tree Shaking的概念。
按名稱導入模塊時,其他模塊不會自動從捆綁中刪除。 捆綁器始終包含代碼中的每個模塊,並忽略您指定為導入名稱的內容。
您未導入的其他未使用的模塊被視為死代碼,因為它們位於捆綁包中,但它們不會被您的代碼調用。
因此,要從捆綁中刪除此未使用的代碼,從而使捆綁更小,您需要一個支持死代碼刪除的minifier。
看看這個流行的樹搖動插件為browserify - 它應該讓你開始:
解決了在browserify轉換中使用rollupify的問題 。 它將執行樹搖動並刪除死代碼:
gulp.task("build_js", () => {
return browserify({
entries: "./public/app/app.js",
cache: {},
dev: true
})
.transform(rollupify, {config: {}}) // <---
.transform(babelify, {presets: ["env"], plugins: ["syntax-async-functions", "transform-async-to-generator"], sourceMaps: true})
.bundle()
.pipe(source("app.bundle.min.js"))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: mode}))
.pipe(uglify())
.pipe(sourcemaps.write("./"))
.pipe(gulp.dest(config.build.js))
});
}
我仍然會理解為什么ES6模塊導入會像這樣工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.