Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

webpack 的 externalType #113

Open
yubaoquan opened this issue May 22, 2024 · 0 comments
Open

webpack 的 externalType #113

yubaoquan opened this issue May 22, 2024 · 0 comments

Comments

@yubaoquan
Copy link
Owner

externalsType 用于标识 webpack 寻找外部模块的策略. 默认是 var

externalsType 有多种类型, 一下摘录其中两种的描述

  • var: Specify the default type of externals as 'var'. Webpack will read the external as a global variable.
  • window: Specify the default type of externals as 'window'. Webpack will read the external as a global variable on the window object.

这两种配置的区别是, var 是根据变量名直接取全局变量, 而 window 是到 window 对象上取某个属性

比如配置了

externals: {
   jquery: 'jQuery'
}

然后 import $ from 'jquery'

那么 `externalType: var` 模式(以下简称 var 模式)得到的大概是
const $ = jQuery

 `externalType: window` 模式(以下简称 window 模式)得到的大概是
const $ = window['jQuery']

这么看来, 两种方式没什么区别. 但是如果一个模块通过 UMD 打包后设置的全局变量名中有中划线, 'foo-bar', 那么 var  window 两种externalsType 导致的行为就不一样了

配置如下:
```javascript
externals: {
  util: 'foo-bar'
}

引用如下:

import util from 'foo-bar'

var 模式会得到

const util = foo-bar

显然被解析成了 foo bar 两个变量的减法表达式, 导致错误 ReferenceError: foo is not defined

window 模式会得到

const util = window['foo-bar']

是预期的结果

如果想在 externalsType='var' 的配置下使用 'foo-bar' 模块, 可以如下配置:

externals: {
  'foo-bar': 'window["foo-bar"]'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant