我正在使用ecma6创建一个简单的应用程序,并尝试使用webpack.ProvidePlugin创建全局变量,但是在从模块内部访问变量时遇到了麻烦。
我的webpack文件:
new webpack.ProvidePlugin({
$: 'jquery/dist/jquery.js',
jQuery: 'jquery/dist/jquery.js',
$chord: [path.resolve(__dirname, 'framework/chord.js'), 'Chord'],
$route: [path.resolve(__dirname, 'framework/router/router.js'), 'Route']
})
我的app.js:
console.log('app.js')
console.log($chord)
console.log($route)
$chord.init()
我的chord.js:
export const Chord = {
globalModules: {},
initGlobalModules (modules) {
this.globalModules = modules
},
render (CurrentView, CurrentModule) {
//here I put the imported module in the window (in this example the home)
$('#app').html(CurrentView);
window.home = CurrentModule;
},
init () {
// so far the variables work on the console
console.log('chord.js')
console.log($route)
this.render($route.routes.root.view, $route.routes.root.module);
}
}
我的home.js
export default {
msgHome () {
console.log('Welcome to Home');
},
navigate () {
// here the global variables not working in console
console.log('home.js')
console.log($chord)
console.log($route)
}
}
运行代码并调用window.home.navigate方法后,控制台显示未定义。应该显示在webpack中定义的全局模块。