Search code examples
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

    • Create a new folder
    • Run npm init -y
    • Install webpack related modules:
      • npm install --save-dev webpack webpack-cli html-loader
    • For intellisense in your editor, install knockout
      • npm install --save-dev knockout
    • Create a npm command in the scripts section:
      • "scripts": { "build": "webpack" }

    Configuring webpack

    • Create a webpack.config.js file:
    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

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

    Creating our entry points

    • Create an index.html
    <!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>
    
    • Create an index.js file
    const ko = require("knockout");
    const greeter = require("./Components/Greeter");
    
    ko.components.register("greeter", greeter);
    ko.applyBindings({});
    

    Build & browser

    • run npm run build, webpack will create a file in a dist folder
    • Open index.html in your browser. It should greet you with a "Hello world"!