webpack 块中未定义的全局 window 变量
Undefined global window variables in webpack chuncks
我正在使用 webpack common chuncks 来定义一个全局库对象(公共组件),它将与其他生成的包一起使用。
常用代码(components.js
)
MyLib = window.MayLib = {}
MyLib.Utils = {
commonFn : function (){
/* common code */
}
}
module.exports = MayLib;
第一个常用用法(dashboard.js
)
require.ensure ('./components', function () {
MyLib.Dashboard = {
/** Dashboad code here */
}
})
第二个常用用法(account.js
)
require.ensure ('./components', function (){
MyLib.Account = {
/** Account code here */
}
})
生成捆绑包后,已创建新的通用代码,但 MyLib is undefined in global window, "cannot set property of undefined"
您可以使用 expose-loader. See also this similar .
解决您的问题
虽然我认为您可以通过在回调中要求 MyLib
对象轻松解决您的问题。无需再将其暴露在全球范围内。
require.ensure ('./components', function (require){
var MyLib = require('./components');
MyLib.Account = {
/** Account code here */
}
})
旁注:您可以尝试使用 CommonsChunkPlugin 来简化代码拆分,然后您只需使用简单的 require('components')
,其余的由插件完成。
我正在使用 webpack common chuncks 来定义一个全局库对象(公共组件),它将与其他生成的包一起使用。
常用代码(components.js
)
MyLib = window.MayLib = {}
MyLib.Utils = {
commonFn : function (){
/* common code */
}
}
module.exports = MayLib;
第一个常用用法(dashboard.js
)
require.ensure ('./components', function () {
MyLib.Dashboard = {
/** Dashboad code here */
}
})
第二个常用用法(account.js
)
require.ensure ('./components', function (){
MyLib.Account = {
/** Account code here */
}
})
生成捆绑包后,已创建新的通用代码,但 MyLib is undefined in global window, "cannot set property of undefined"
您可以使用 expose-loader. See also this similar
虽然我认为您可以通过在回调中要求 MyLib
对象轻松解决您的问题。无需再将其暴露在全球范围内。
require.ensure ('./components', function (require){
var MyLib = require('./components');
MyLib.Account = {
/** Account code here */
}
})
旁注:您可以尝试使用 CommonsChunkPlugin 来简化代码拆分,然后您只需使用简单的 require('components')
,其余的由插件完成。