1、首先需要node(去官网下载)
2、见一个文件夹 比如koa cmd——r cd koa文件
3、npm init
4、安装webpack (本地安装)
npm install --save-dev webpack
4.1、用webpack4+ 还需要安装webpack-cli
npm install --save-dev webpack-cli
5、安装koa (记住,package.json内的项目名称不能叫koa 否则安装不了koa)
npm install koa --save
6、安装其他依赖
npm install koa-compress --save npm install koa-router --save npm install koa-compress --save npm install koa-static --save
package.json文件
{ "name": "testKoa", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "serve":"node app.js" }, "author": "", "license": "ISC", "devDependencies": { "webpack": "^4.31.0", "webpack-cli": "^3.3.2" }, "dependencies": { "koa": "^2.7.0", "koa-compress": "^3.0.0", "koa-router": "^7.4.0", "koa-static": "^5.0.0" } }
app.js
const koaStatic = require("koa-static"); const compress = require("koa-compress"); const path = require("path"); const fs = require("fs"); const app = new Koa(); app.use(compress()); app.use(koaStatic(path.resolve(__dirname,"./"))); const router = koaRouter(); router.get("*",async(ctx,next)=>{ ctx.type="html", ctx.body=fs.readFileSync(path.resolve('./dist/index.html'),'utf-8') }); app.use(router.routes()).use(router.allowedMethods()); app.listen(3000,()=>{ console.log("server run on localhost:3000"); })
将dist的文件放到跟目录
运行npm run serve