【问题标题】:Can I force import dependency as pure?我可以强制导入依赖为纯吗?
【发布时间】:2021-02-27 18:14:18
【问题描述】:
例如,我在我的库中使用mustache,但它仅用于可导出函数
import mustache from 'mustache'
export function some() {
...
mustache
...
}
export function other() {
...
}
当我从这个库中只导入other 并使用webpack 构建包时,webpack 包含mustache 的代码,因为它认为mustache 的代码不纯。
我能以某种方式将mustache 导入标记为纯吗?
【问题讨论】:
标签:
javascript
webpack
tree-shaking
【解决方案1】:
我认为 Webpack 在您导入时总是会捆绑 mustache。
也许您可以将您的库拆分为多个文件:
some.js
import mustache from 'mustache'
export default function some() {
...
mustache
...
}
和other.js
export default function other() {
...
}
并创建主index.js 文件,这是默认导出并结合上述内容:
import some from './some';
import other from './other';
export default {
some,
other,
};
通过这种方式,您的库可以整体使用(通过 index.js)或部分使用 - some.js 或 other.js(其中不包括 mustache)。
// you can use the whole library as
import library from 'library';
// or you can use any part, for example 'other' (without mustache)
import other from 'library/other';