koa项目配置
热加载
nodemon 是一个工具,它通过在检测到目录中的文件更改时自动重新启动节点应用程序来帮助开发基于 Node.js 的应用程序。
npm i nodemon -D
"scripts": {
"dev": "nodemon ./src/index.js"
},
npm run dev 启动
webpack配置
安装
npm i webpack webpack-cli -D
npm i clean-webpack-plugin -D
npm i webpack-node-externals -D
npm i @babel/core @babel/node @babel/preset-env babel-loader -D
npm i cross-env -D
npm i webpack-merge -D
npm install terser-webpack-plugin ---save-dev
npm i rimraf -D
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 --help
ncu -u
rm -rf node_modules/
webpack整合
- 项目目录新建config文件夹
- 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')
- 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
- 开发环境配置: 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' ,
status: { children: false }
})
module.exports = webpackConfig
- 生产环境配置: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',
optimization: {
nodeEnv: false,
minimize: true,
minimizer: [
new TerserWebpackPlugin({
terserOptions: {
ecma: undefined,
parse: {},
compress: {
warnings: false,
drop_console: false,
dead_code: true,
drop_debugger: true
},
mangle: true,
module: false,
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
- 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
class DemoController {
constructor () {}
async demo(ctx) {
ctx.body = {
msg: 'body message'
}
}
}
export default new DemoController()
import Router from "koa-router"
import demoController from "../api/demoController"
const router = new Router()
router.get('/demo', demoController.demo)
export default router
const combineRouters = require('koa-combine-routers')
import demoController from './demoRouter'
export default combineRouters(demoController)
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
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)
- 运行
|