koa框架(二)

koa项目配置

热加载

nodemon 是一个工具,它通过在检测到目录中的文件更改时自动重新启动节点应用程序来帮助开发基于 Node.js 的应用程序。

  • 安装
npm i nodemon -D
  • 使用
    在package.json中配置
 "scripts": {
    "dev": "nodemon ./src/index.js"
  },
npm run dev 启动

webpack配置

安装

  • webpcak常用包
npm i webpack webpack-cli -D
// 清理dist文件
npm i clean-webpack-plugin -D
// 对node_modules下的一些文件做排除处理
npm i webpack-node-externals -D
// babel相关
npm i @babel/core @babel/node @babel/preset-env babel-loader -D
// 设置环境变量
npm i cross-env -D
// 合并webpack配置
npm i webpack-merge -D
// 压缩打包的代码
npm install terser-webpack-plugin ---save-dev
// 清空dist
npm i  rimraf -D
  • webpack.config.js配置babel
const path = require('path')
// 排除不会使用到的模块
const nodeExcternals = require('webpack-node-externals')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const webpackConfig = {
  target: 'node',
  mode: 'development',
  entry: {
    server: path.join(__dirname,'src/index.js')
  },
  output: {
    filename: '[name].bundle.js',
    path: path.join(__dirname, './dist'),
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: {
          loader: 'babel-loader',
        },
        exclude: [path.join(__dirname, '/node_modules')]
      }
    ]
  },
  devtool: 'eval-source-map',
  externals: [nodeExcternals()],
  plugins: [
    new CleanWebpackPlugin()
  ]
}
module.exports = webpackConfig**

webpack配置了babel后可以使用es6语法

  • 运行
npx babel-node src/index.js

webpack调试

在Chrome中调试
  • 调试命令
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon ./src/index.js",
    "start": "nodemon --exec babel-node src/index.js",
    "webpack:debug": "node --inspect-brk ./node_modules/./webpack --inline --progress"
  },
  • 运行
npm run webpack:debug
  • 浏览器调试
    在这里插入图片描述
在VScode中调试
  • 添加nodemon配置并运行,在代码中打断点调试
    在这里插入图片描述

优化webpack配置

  • 检查项目中是否有依赖包更新
npm install -g npm-check-updates

// 查看ncu 指令
ncu --help

// 更新package.json
ncu -u

// 更新后删除node_modules 重新安装
rm -rf node_modules/
 
webpack整合
  1. 项目目录新建config文件夹
  2. config目录新建utils.js,配置路径
const path = require('path')

exports.resolve = function resolve(dir) {
  return path.join(__dirname, '..', dir)
}
exports.APP_PATH = exports.resolve('src')
exports.DIST_PATH = exports.resolve('dist')
  1. webpack.config.base.js
const path = require('path')
// 排除不会使用到的模块
const nodeExcternals = require('webpack-node-externals')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const webpack = require('webpack')
const utils = require('./utils')
const webpackConfig = {
  target: 'node',
  entry: {
    server: path.join(utils.APP_PATH,'index.js')
  },
  output: {
    filename: '[name].bundle.js',
    path: utils.DIST_PATH,
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: {
          loader: 'babel-loader',
        },
        exclude: [path.join(__dirname, '/node_modules')]
      }
    ]
  },

  externals: [nodeExcternals()],
  plugins: [
    new CleanWebpackPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'prod') ? "'production'" : "'development'"
      }
    })
  ]
}
console.log('webpackConfig', webpackConfig)
module.exports = webpackConfig
  1. 开发环境配置: webpack.config.dev.js
const webpackMerge = require('webpack-merge')

const baseWebpackConfig = require('./webpack.config.base')

const webpackConfig = webpackMerge(baseWebpackConfig, {
  devtool: 'eval-source-map', 
  mode: 'development' ,
  // webpack输入消息日志不需要传递出来
  status: { children: false }
})
module.exports = webpackConfig
  1. 生产环境配置:webpack.config.prod.js
const webpackMerge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.config.base')

const TerserWebpackPlugin = require('terser-webpack-plugin')

const webpackConfig = webpackMerge.merge(baseWebpackConfig, {
  mode: 'production',
  // status: { children: false },
  optimization: {
    // webpack5 在不设置时(一般都不会设置),默认读取mode的值(默认是production或development),DefinePlugin重新设置时与mode不一致,导致冲突
    nodeEnv: false,
    minimize: true,
    minimizer: [
      new TerserWebpackPlugin({
        terserOptions: {
          ecma: undefined,
          parse: {},
          compress: {
            warnings: false,
            // 是否注释console
            drop_console: false,
            dead_code: true,
            drop_debugger: true
          },
          mangle: true, // Note `mangle.properties` is `false` by default.
          module: false,
          // Deprecated
          output: {
            comments: false,
            beautify: false
          },
          format: null,
          toplevel: false,
          nameCache: null,
          ie8: false,
          keep_classnames: undefined,
          keep_fnames: false,
          safari10: false,
        },
      }),
    ],
    splitChunks: {
      cacheGroups: {
        commons: {
          name: 'commons',
          chunks: 'initial',
          minChunks: 3,
          enforce: true
        },
      },
    },
  },
})
module.exports = webpackConfig
  1. package.js scripts新增
{
  "name": "koa_web",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "nodemon": "nodemon ./src/index.js",
    "start": "nodemon --exec babel-node src/index.js",
    "webpack:debug": "node --inspect-brk ./node_modules/./webpack --inline --progress",
    "build": "cross-env NODE_ENV=production webpack --config config/webpack.config.prod.js",
    "dev": "cross-env NODE_ENV=dev nodemon --exec babel-node --inspect ./src/index.js",
    "clean": "rimraf dist"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@koa/cors": "^3.3.0",
    "koa": "^2.13.4",
    "koa-body": "^5.0.0",
    "koa-combine-routers": "^4.0.2",
    "koa-compose": "^4.1.0",
    "koa-compress": "^5.1.0",
    "koa-helmet": "^6.1.0",
    "koa-json": "^2.0.2",
    "koa-router": "^12.0.0",
    "koa-static": "^5.0.0"
  },
  "devDependencies": {
    "@babel/core": "^7.18.10",
    "@babel/node": "^7.18.10",
    "@babel/preset-env": "^7.18.10",
    "babel-loader": "^8.2.5",
    "clean-webpack-plugin": "^4.0.0",
    "cross-env": "^7.0.3",
    "nodemon": "^2.0.19",
    "rimraf": "^3.0.2",
    "terser-webpack-plugin": "^5.3.4",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0",
    "webpack-merge": "^5.8.0",
    "webpack-node-externals": "^3.0.0"
  }
}

完整koa demo

  • 项目目录

  • api/demoController.js
class DemoController {
  constructor () {}
  async demo(ctx) {
    ctx.body = {
      msg: 'body message'
    }
  }
}
export default new DemoController()
  • routers/demoRouter.js
import Router from "koa-router"
import demoController from "../api/demoController"
const router = new Router()

router.get('/demo', demoController.demo)

export default router

  • routers/routes.js
const combineRouters = require('koa-combine-routers')
import demoController from './demoRouter'

export default combineRouters(demoController)
  • src/index.js
import koa from 'koa'
import router from './routers/routes'
import cors from '@koa/cors'
import koabody from 'koa-body'
import json from 'koa-json'
import path from 'path'
import koaHelmet from 'koa-helmet'
import statics from 'koa-static'
import compose from 'koa-compose'
import compress from 'koa-compress'

const app = new koa()

// 是否为开发模式
const isDevMode = process.env.NODE_ENV === 'production' ? false : true

// koa-compose 整合中间件
const middleware = compose([
  koabody(),
  statics(path.join(__dirname, '../public')),
  cors(),
  json({ pretty: false, param: 'pretty'}),
  koaHelmet()
])

// 如果是生产模式就压缩中间件
if (!isDevMode) {
  app.use(compress())
}

app.use(middleware)
app.use(router())

app.listen(3000)
  • 运行
    在这里插入图片描述
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Node.js 中使用 Koa 框架进行事务管理可以使用以下两种方式: 1. 使用数据库事务:如果你使用的是支持事务的数据库(如 MySQL、PostgreSQL 等),那么你可以使用数据库提供的事务功能来管理事务。在 Koa 中,你可以使用像 Sequelize 这样的 ORM 库来管理数据库操作。 例如,在 Sequelize 中使用事务的代码示例: ``` // 创建一个事务 const transaction = await sequelize.transaction(); try { // 在事务中执行数据库操作 await User.create({ name: 'John Doe' }, { transaction }); await Profile.create({ userId: 1, bio: 'Hello, world' }, { transaction }); // 提交事务 await transaction.commit(); } catch (error) { // 回滚事务 await transaction.rollback(); } ``` 在上面的示例中,我们使用了 `sequelize.transaction()` 方法来创建一个事务,并将其传递给每个数据库操作。如果其中任何一个操作失败,那么事务将会回滚,所有操作都将被撤销。 2. 使用 Koa 中间件:另一种管理事务的方法是使用 Koa 中间件来实现。你可以编写一个中间件函数,将所有需要在事务中执行的操作包裹起来,并在出现错误时回滚事务。 例如,在 Koa 中使用中间件管理事务的代码示例: ``` app.use(async (ctx, next) => { const transaction = await sequelize.transaction(); try { // 将事务对象绑定到上下文对象中 ctx.transaction = transaction; // 执行下一个中间件 await next(); // 提交事务 await transaction.commit(); } catch (error) { // 回滚事务 await transaction.rollback(); // 抛出错误 throw error; } }); // 在路由中使用事务 router.post('/users', async (ctx) => { // 从上下文对象中获取事务对象 const transaction = ctx.transaction; try { // 在事务中执行数据库操作 await User.create({ name: 'John Doe' }, { transaction }); await Profile.create({ userId: 1, bio: 'Hello, world' }, { transaction }); // 发送响应 ctx.body = { success: true }; } catch (error) { // 如果发生错误,将会自动回滚事务 throw error; } }); ``` 在上面的示例中,我们编写了一个 Koa 中间件函数,该函数会在每个请求中创建一个事务,并将其绑定到上下文对象中。在路由处理函数中,我们可以从上下文对象中获取事务对象,并使用它来执行数据库操作。如果任何一个操作失败,中间件将会回滚事务,并将错误抛出到全局错误处理函数中。 总的来说,使用数据库事务或 Koa 中间件来管理事务都是有效的方式。选择哪种方式取决于你的具体需求和项目的架构。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值