Search code examples
javascripttypescriptknockout.jswebpackwebpack-2

webpack2 tree-shaking with knockout templates


I am using webpack to bundle my typescript project and I am using knockout as my templating engine.

Now, when I build my project for production it stops working - a knockout template is complaining that a property is not defined.

I have the suspicion that the tree-shaking algorithm of webpack2 is removing that property because it isn't used in any typescript code, but only in a knockout data-bind string.

Is there a way to tell webpack to always include a certain property even when it thinks it isn't used?


Solution

  • I'm not that familiar with webpack, but I've ran in to the same problem with google closure compiler. It would remove properties only used in data-binds and obfuscate others...

    The solution direction that worked for me was one that knockout itself also uses in its source: ko.exportProperty

    It's used like so:

    var VM = function() {
      this.somePropOnlyUsedInView = "Hello world";
    
      ko.exportProperty(this, "somePropOnlyUsedInView", this.somePropOnlyUsedInView);
    }
    

    The method does two things:

    • It uses the obj["string"] notation to force the property name
    • It actually references the property, making the minifier think it is used and cannot be removed.

    Let me know if this utility also works for your webpack based build process, I'm curious to know.