[英]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.