是否可以配置 Webpack,使其 tree-shaking 足够智能以删除仅依赖于其他 tree-shaken 导出的导入?
例子:
entry.js
import { apple } from './appleBanana';
console.log(apple());
appleBanana.js
import { mango, orange } from './mangoOrange';
export function apple() {
console.log('apple');
mango();
}
export function banana() {
console.log('banana');
orange();
}
芒果橙.js
export function mango() {
console.log('mango');
}
export function orange() {
console.log('orange');
}
webpack.config.js优化
optimization: {
concatenateModules: false,
usedExports: true,
sideEffects: true
}
使用上述编译时,我们得到:
/***/ "./client/entry/Test.ts":
/*!******************************!*\
!*** ./client/entry/Test.ts ***!
\******************************/
/*! no exports provided */
/*! all exports used */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _appleBanana__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./appleBanana */ "./client/entry/appleBanana.ts");
console.log(Object(_appleBanana__WEBPACK_IMPORTED_MODULE_0__[/* apple */ "a"])());
/***/ }),
/***/ "./client/entry/appleBanana.ts":
/*!*************************************!*\
!*** ./client/entry/appleBanana.ts ***!
\*************************************/
/*! exports provided: apple, banana */
/*! exports used: apple */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return apple; });
/* unused harmony export banana */
/* harmony import */ var _mangoOrange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./mangoOrange */ "./client/entry/mangoOrange.ts");
function apple() {
console.log('apple');
return Object(_mangoOrange__WEBPACK_IMPORTED_MODULE_0__[/* mango */ "a"])();
}
function banana() {
console.log('banana');
return Object(_mangoOrange__WEBPACK_IMPORTED_MODULE_0__[/* orange */ "b"])();
}
/***/ }),
/***/ "./client/entry/mangoOrange.ts":
/*!*************************************!*\
!*** ./client/entry/mangoOrange.ts ***!
\*************************************/
/*! exports provided: mango, orange */
/*! exports used: mango, orange */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return mango; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return orange; });
function mango() {
console.log('mango');
}
function orange() {
console.log('orange');
}
/***/ })
/******/ });
请注意,两者mango
和orange
都被标记为已使用,即使banana()
(调用orange()
)已被摇树删除。因此,在 Terser/Uglify 缩小包中,它们都被包含在内。
有没有办法让 Webpack 或 Terser/UglifyJS 更智能,并且还可以删除对树后摇动中未使用的符号的导入?