I have a front end SPA written in Knockout. Due to its size, I want to split it into multiple files, making my folder structure look something like this:
node_modules
|- knockout
\- requirejs
components
|- MyFutureViewModel.js
\- etc.
index.html
app.js
Index.html looks something like this:
<!DOCTYPE html>
<html>
<head>
<title>NCounter</title>
<meta charset="utf-8">
<script type="text/javascript" data-main="app.js" src="./node_modules/requirejs/require.js"></script>
</head>
<body>
<p>The name is <input data-bind="value: name" /></p>
<p>You entered <span data-bind="text: name"></span>.</p>
</body>
</html>
My app.js file looks something like this:
requirejs.config({
//Pass the top-level main.js/index.js require
//function to requirejs so that node modules
//are loaded relative to the top-level JS file.
nodeRequire: require
});
require(['knockout'], function(ko) {
var viewModel = function() {
name: ko.observable('name')
};
ko.applyBindings(viewModel);
});
However, requirejs does not appear to see knockout. Is there a configuration or step I'm missing?
You have to modify your RequireJS config
requirejs.config({
baseUrl: "node_modules/",
paths: {
// assuming that knockout lives in the node_modules/knockout/knockout.js file
// if not, you have to specify relative to `node_modules` path
// without .js extension
'knockout': 'knockout/knockout',
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With