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
Here's how to set up a "Hello world" app from scratch:
npm init -y
npm install --save-dev webpack webpack-cli html-loader
npm install --save-dev knockout
"scripts": { "build": "webpack" }
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"
}
}
Components
Greeter.html
<h1 data-bind="text: message">...</h1>
Greeter.js
const greeterTemplate = require("./Greeter.html");
module.exports = {
viewModel: function(params) {
this.message = params.message;
},
template: greeterTemplate
};
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>
index.js
fileconst ko = require("knockout");
const greeter = require("./Components/Greeter");
ko.components.register("greeter", greeter);
ko.applyBindings({});
npm run build
, webpack will create a file in a dist
folderindex.html
in your browser. It should greet you with a "Hello world"!