Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load front end NPM/Yarn packages with RequireJS

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?

like image 456
John Avatar asked Nov 18 '22 13:11

John


1 Answers

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

like image 103
codevision Avatar answered Dec 06 '22 12:12

codevision