首页 > 解决方案 > 我可以强制导入依赖为纯吗?

问题描述

例如,我mustache在我的库中使用,但它仅用于可导出功能

import mustache from 'mustache'

export function some() {
  ...
  mustache
  ...
}

export function other() {
  ...
}

当我只other从这个库导入并使用 webpack 构建包时,webpack 包含mustache的代码,因为它认为什么代码mustache不纯。

我可以以某种方式将mustache导入标记为纯吗?

标签: javascriptwebpacktree-shaking

解决方案


mustache我认为 Webpack在您导入时总是会捆绑。

也许您可以将库拆分为几个文件:

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.jsother.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';

推荐阅读