I'm working on moving some legacy code into Webpack (to help me control some dependancy hell that I'm having. All's going well so far. The issue comes from the existing codes use of Knockout. I need a way to access the view model in various components. So I need something to hold this view model. This question seems to provide me a good solution:
Put your variables in a module.
Webpack evaluates modules only once, so your instance remains global and carries changes through from module to module. So if you create something like a globals.js and export an object of all your globals then you can import './globals' and read/write to these globals.
I can't really figure out how to do this though. I'm pretty new to webpack/import
/export
statements so I'm not up to date on the fundamentals. I want a "Module". Great what does webpack have to say on this:
What is a webpack Module
In contrast to Node.js modules, webpack modules can express their dependencies in a variety of ways
What? Really, that's it?! So I'm struggling to come to terms with what a module is and how I should use one?
Up till now I've defined exported functions and imported them (are these modules??!). So I would do something like this:
export default function koModule(){
var viewModel = {}
function setViewModel(vm){
viewModel = vm;
}
function getViewModel(){
return viewModel;
}
return {
setViewModel:setViewModel,
getViewModel : getViewModel
}
}
I'm think I can then kinda use this when I create my initial viewmodel:
import koModule from './koModule.js'
...
//obviously wrong....
var myKoModule = koModule();
myKoModule.setViewModel(vm);
...
But that's obviously wrong as the myKoModule
will be instantiated every time I call the function... and any module trying to do read it is just going to get a blank object:
import koModule from './koModule.js'
...
//obviously wrong....
var myKoModule = koModule();
var vm = myKoModule.getViewModel();
//vm is undefined...
In the previous question it states "Webpack evaluates modules only once". So I'm obviously missing what a module is and how I should be using them then.
So given my requirements, can someone provide an example of a working Webpack "Module" and it's usage in holding,reading and writing a global variable while still allowing me to import
it?
I'm obviously missing something fundamental here but I can't really figure out what it is.
This is about as close I can get for you without knowing exactly how you want to use your models and what not. This is often how I use viewModels in webpack, they are essentially just constructor functions with built in methods that I can call on when needed.
Main.js
KoModule.js
HTML
Working example here