koa-webpack-javascript
一、初始化
yarn init -y
二、安装依赖
2.1 Koa 依赖
yarn add koa koa-router -S
2.2 其他依赖
yarn add nodemon npm-run-all -D
2.3 Babel 依赖
yarn add core-js babel-loader @babel/core @babel/preset-env @babel/plugin-transform-runtime -D
2.4 Webpack 依赖
yarn add webpack webpack-cli clean-webpack-plugin -D
三、构建入口
import Koa from "koa";
const app = new Koa();
const requireAll = (context) => context.keys().map((key)=>{
return context(key);
});
const requireContext = require.context("./router", false, /\.js$/);
requireAll(requireContext).forEach(item=>{
let router=item.default;
app.use(router.routes()).use(router.allowedMethods());
});
app.listen(8090, () => {
console.log("服务启动成功!");
});
四、构建路由
import Router from 'koa-router';
import Controller from '../controller/index';
const router = new Router({prefix:'/'});
router.get('/',Controller.get);
export default router;
:::
:::details src>controller>index.js
const get = async (ctx)=>{
ctx.body={
code:0,
msg:'成功!'
}
}
export default {
get
}
五、配置 babel
babel.config.js
const presets = [
[
"@babel/preset-env",
{
useBuiltIns: "usage",
corejs: "3.11.0",
},
],
];
const plugins = ["@babel/plugin-transform-runtime"];
module.exports = {
presets,
plugins,
};
六、配置 webpack
const Path = require('path');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
module.exports={
target:'node',
mode:'development',
entry:Path.resolve(process.cwd(),'./src/app.js'),
output:{
path:Path.resolve(process.cwd(),'build'),
filename:'app.js'
},
module:{
rules:[
{
test:/\.js$/,
loader:'babel-loader',
exclude:/node_modules/,
}
]
},
plugins:[
new CleanWebpackPlugin()
]
}
七、依赖、命令管理
{
"name": "struct-webpackKoa",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"server":"npm-run-all --parallel server:**",
"server:build": "webpack --config ./config/webpack.config.js --watch",
"server:reServer": "nodemon --watch build --exec node build/app.js"
},
"devDependencies": {
"@babel/core": "^7.16.0",
"@babel/plugin-transform-runtime": "^7.16.0",
"@babel/preset-env": "^7.16.0",
"babel-loader": "^8.2.3",
"clean-webpack-plugin": "^4.0.0",
"core-js": "^3.19.1",
"webpack": "^5.64.0",
"webpack-cli": "^4.9.1"
},
"dependencies": {
"koa": "^2.13.4",
"koa-router": "^10.1.1",
"nodemon": "^2.0.15",
"require-all": "^3.0.0"
}
}