【问题标题】:Is it possible to import a bundled webpack and library separately using webpack?是否可以使用 webpack 分别导入捆绑的 webpack 和库?
【发布时间】:2018-05-08 15:06:43
【问题描述】:

我正在尝试构建一个使用 d3 的模块,但我不想将 d3 与该模块捆绑在一起,而且最重要的是,我不想将 d3 绑定到窗口。该模块将安装在另一个项目中,npm 作为 git 依赖项。在模块上我有这样的设置:

output: {
    path: path.resolve(__dirname, '../dist'),
    filename: '[name].min.js',
    libraryTarget: 'umd',
    umdNamedDefine: true
  },
  externals: [
    {
      "d3": {
        root: "d3"
      }
    }
  ]

并且在它安装到的项目中,我想要这样的东西:

import d3 from 'd3'
import example from 'example'

但是,只有在我也这样做时才有效:

import d3 from 'd3'
window.d3=d3
import example from 'example'

是否可以在不触及全局范围的情况下同时使用这两个模块?

【问题讨论】:

    标签: npm webpack umd


    【解决方案1】:

    尝试改变

      externals: [
        {
          "d3": {
            root: "d3"
          }
        }
      ]
    

      externals: [
        {
          "d3": {
            commonjs: "d3"
          }
        }
      ]
    

    Descried in the doc。通过设置为root,库应该可以作为全局变量使用

    【讨论】:

      【解决方案2】:

      因为这两个模块是分开存在的,所以它们都有自己的闭包。共享第三个依赖项的唯一地方是两者外部的范围,传统上是全局范围。 你可以练习依赖注入。

      所以,而不是

      module.exports = function do_a_thing() {
        // use d3 here
      }
      

      你会的

      module.exports = function do_a_thing_generator(d3) {
        return function do_a_thing() {
          // use d3 here
        }
      }
      

      然后,最终

      import d3 from 'd3'
      import exampleInit from 'example'
      
      const example = exampleInit(d3)
      

      【讨论】:

        猜你喜欢
        • 2020-11-10
        • 1970-01-01
        • 2021-04-28
        • 1970-01-01
        • 2016-05-28
        • 1970-01-01
        • 2016-07-05
        • 2016-09-26
        • 2019-07-16
        相关资源
        最近更新 更多