6

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?

1 Answer 1

1

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', } });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.