javascriptwebpackknockout.jsknockout-components

Simple demo project Webpack KO(with a components) javascript


I want to build a SPA with javascript knockout components After lots of reading and fiddling I still can't seem to get a working javascript(no typescript) knockout( with components) project with webpack. I found simple knockout projects but can't get them working with webpack.

Does someone have a demo project wit at least one ko component using webpack?

The Yeoman generator-ko-spa (in javascript) working with Webpack would be great.

Thnx


Solution

  • Here's how to set up a "Hello world" app from scratch:

    Installing packages

    Configuring webpack

    const path = require("path");
    
    module.exports = {
      entry: path.resolve(__dirname, "index.js"),
      module: {
        rules: [
          // This tells webpack to import required html files
          // as a string, through the html-loader
          { test: /\.html$/, use: [ "html-loader" ] }
        ],
      },
      // You *could* include knockout in your bundle, 
      // but I usually get it from a CDN
      externals: {
        knockout: "ko"
      }
    }
    

    Creating our component viewmodel & view

    <h1 data-bind="text: message">...</h1>
    
    const greeterTemplate = require("./Greeter.html");
    
    module.exports = {
      viewModel: function(params) {
        this.message = params.message;
      },
      template: greeterTemplate
    };
    

    Creating our entry points

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <title>Document</title>
    </head>
      <body>
        <greeter params="message: 'Hello world!'"></greeter>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
        <script src="dist/main.js"></script>
      </body>
    </html>
    
    const ko = require("knockout");
    const greeter = require("./Components/Greeter");
    
    ko.components.register("greeter", greeter);
    ko.applyBindings({});
    

    Build & browser