以下是从头开始设置“Hello world”应用程序的方法:
安装软件包
- 新建一个文件夹
- 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" }
配置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
- Create
Greeter.html
<h1 data-bind="text: message">...</h1>
const greeterTemplate = require("./Greeter.html");
module.exports = {
viewModel: function(params) {
this.message = params.message;
},
template: greeterTemplate
};
创建我们的入口点
<!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({});
构建和浏览器
- run
npm run build
,webpack 将在 a 中创建一个文件dist
folder
- Open
index.html
在您的浏览器中。它应该用“Hello world”向您打招呼!