Search code examples
knockout.jsbrowserifycommonjsbrowserify-shimknockout-projections

Use Browserify + Knockout + Knockout projections


I am trying to include both knockout and knockout-projections in a project with Browserify. I am using browserify-shim to bind it all together.

Unfortunately the knockout-projections code fails when it requires knockout, either with a compile-time error or a runtime error – depending on the setup of the shim.

To illustrate the problem I have set up a github repository: brianmhunt/bshim-ko-testcase.


Solution

  • @brianmhunt, still not an issue with browserify.

    Your latest change on the repo installs both knockout and knockout-projections via bower. That is fine.

    However, each bower component also has a package.json. This would not be an issue either, but the package.json file in knockout-projections specifies knockout as a dependancy as well.

    Between the "browser" setting you have in your own package.json and knockout-projections also calling "require('knockout')" in its code, it's kinda of a catch-22 in this scenario.

    A couple of workarounds:

    • delete the package.json file in the knockout-projections directory
    • run "npm install" in the knockout-projections directory (see gotchas below)

    Alternative: (install via npm):

    {
      "name": "bshim-ko-test",
      "version": "0.0.3",
      "repository": "https://github.com/brianmhunt/bshim-ko-testcase",
      "browser": {
        "koproj": "knockout-projections"
      },
      "main": "./test.js",
      "dependencies" : {
        "knockout" : "~3.0.0",
        "knockout-projections" : "SteveSanderson/knockout-projections"
      }
    }
    

    Now your steps will be:

    • git clone <repository>
    • npm install browserify -g
    • cd <repository>, and "npm install"
    • browserify test.js -o bundle.js

    Gotchas:

    • Be careful doing either second workaround above, or the alternate. If your Knockout versions don't match, you get both copies of Knockout in bundle.js. Definately, not what your expecting.
    • The package.json files in Knockout and KO Projections are pointing to debug files (not minified) This will make your bundle.js quite large.