【问题标题】: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.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';
    

    【讨论】:

      猜你喜欢
      • 2011-11-18
      • 1970-01-01
      • 1970-01-01
      • 2012-03-07
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 2013-07-27
      • 2014-11-15
      相关资源
      最近更新 更多