WebPack 2:用 global 替换了 require'd 模块
WebPack 2: Replaced require'd module with global
正在编写一组脚本,这些脚本将 运行 在某些模块(例如下划线)将作为全局模块提供的浏览器上下文中使用。但是,我依赖于 node_modules
中 require
/ import
直接下划线的模块。是否可以将 WebPack 配置为在编译这些文件时依赖于全局下划线实例,而不是在我编译的脚本中复制该库?
如果你想在加载包时依赖环境中已经可用的库,你需要使用 externals。
module.exports = {
externals: {
underscore: "_"
}
}
对象的键 (underscore
) 是你用来导入它的,值 (_
) 是它要查找的全局变量。
require("underscore"); // Will return the _ variable from the global environment!
您要找的是Externals:
externals
configuration in webpack provides a way of not including a dependency in the bundle. Instead the created bundle relies on that dependency to be present in the consumers environment. This typically applies to library developers though application developers can make good use of this feature too.
这甚至适用于 node_modules
中的模块,因为 webpack 遍历 整个 依赖关系树以找出要包含在生成的包中的内容。
甚至还有一个 example 专门针对您的用例,它看起来像:
externals : {
lodash : {
commonjs: "lodash",
amd: "lodash",
root: "_" // indicates global variable
}
}
This syntax is used to describe all the possible ways that an external library can be available. lodash here is available as lodash under AMD and CommonJS module systems but available as _ in a global variable form.
正在编写一组脚本,这些脚本将 运行 在某些模块(例如下划线)将作为全局模块提供的浏览器上下文中使用。但是,我依赖于 node_modules
中 require
/ import
直接下划线的模块。是否可以将 WebPack 配置为在编译这些文件时依赖于全局下划线实例,而不是在我编译的脚本中复制该库?
如果你想在加载包时依赖环境中已经可用的库,你需要使用 externals。
module.exports = {
externals: {
underscore: "_"
}
}
对象的键 (underscore
) 是你用来导入它的,值 (_
) 是它要查找的全局变量。
require("underscore"); // Will return the _ variable from the global environment!
您要找的是Externals:
externals
configuration in webpack provides a way of not including a dependency in the bundle. Instead the created bundle relies on that dependency to be present in the consumers environment. This typically applies to library developers though application developers can make good use of this feature too.
这甚至适用于 node_modules
中的模块,因为 webpack 遍历 整个 依赖关系树以找出要包含在生成的包中的内容。
甚至还有一个 example 专门针对您的用例,它看起来像:
externals : {
lodash : {
commonjs: "lodash",
amd: "lodash",
root: "_" // indicates global variable
}
}
This syntax is used to describe all the possible ways that an external library can be available. lodash here is available as lodash under AMD and CommonJS module systems but available as _ in a global variable form.