是否可以使用webpack单独导入捆绑的webpack和库?

问题描述 投票:0回答:2

我正在尝试构建一个使用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
2个回答
0
投票

尝试改变

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

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

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


0
投票

因为这两个模块是分开存在的,所以每个模块都有自己的闭包。共享第三个依赖关系的唯一地方是两个传统全局范围之外的范围。您可以练习依赖注入。

所以,而不是

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)
© www.soinside.com 2019 - 2024. All rights reserved.