创建目录结构如下:
koa-demo
|—-src
|—-api
|—-a.js
|—-b.js
|—-routes
|—-aRouter.js
|—-bRouter.js
|—-routes.js
|—-index.js
**
Koa 热加载
$ npm install -D nodemon # 安装到开发模式
之后可以在node_modules/.bin下的nodemon文件
我们可以输入命令查看 nodemon 的版本号
$ ./node_modules/.bin/nodemon --version # 如果装有 npx 直接: npx nodemon --version
启动 nodemon
$ npx nodemon src/index.js
之后不论修改目录中任何文件,都会重新运行项目
在 package.json 文件添加 start 命令,后面接一个 nodemon 脚本,我们就可以使用 npm run start 来运行nodemon 啦,示例如下:
"scripts": {"start": "nodemon src/index"}
让项目支持 ES6 语法:webpack
安装对应版本的 webpack 和 webpack-cli ,和其他一些常用的包
$ npm i -D webpack@4 webpack-cli@3
$ npm install -D clean-webpack-plugin webpack-node-externals @babel/core @babel/node @babel/preset-env babel-loader cross-env
webpack 包介绍:
clean-webpack-plugin
webpack-node-externals
主要是为了对node_modules下面的文件做一个排除处理,
排除我们项目中没有使用到的模块
@babel/core
@babel/node
babel转义后的ES6+语法可以被大部分浏览器支持,但是node环境不支持
使得node环境支持babel
@babel/preset-env
可以根据配置的目标浏览器或者运行环境来自动将ES6+的代码转换为es5
可以对一些很新的特性做一些支持
cross-env
设置环境变量,可以程序判断当前是开发还是生产环境,来使用不同的方法去处理
babel-loader
webpack中需要使用到的babel的Loader
之后在根目录下创建 webpack.config.js 文件
const path = require('path')const nodeExternals = 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') // 打包之后存放的目录},devtool: 'eval-source-map',module: {rules: [{test: /\.(js|jsx)$/, // 匹配目录下所有 js 文件use: {loader: 'babel-loader'},exclude: [path.join(__dirname, 'node_modules')] // 排除}]},externals: [nodeExternals()],plugins: [new CleanWebpackPlugin()],// node 里的配置需要对应的 webpack 和 webpack-cli 版本,// 链接:https://www.webpackjs.com/configuration/node/node: {console: true,global: true,process: true,Buffer: true,__filename: true,__dirname: true,setImmediate: true,path: true}}module.exports = webpackconfig
并且创建 .babelrc 文件,配置 babel-loader
{"presets": [["@babel/preset-env",{"targets": {"node": "current"}}]]}
$ npx webpack
打包之后会生成一个 dist 目录,之后可以在项目中使用 ES6语法,因为有了 babel
/src/index.js
import koa from 'koa'import path from 'path'// 安全头import helmet from 'koa-helmet'// 静态资源import statics from 'koa-static'// 路由import router from './routes/routes'const app = new koa();app.use(helmet())app.use(statics(path.join(__dirname, '../public')))app.use(router())app.listen(3000)
现在不可以直接使用 node /src/index.js 了,因为 nodejs 使用的是 Commonjs的模块化规范。所以,需要 babel 来进行转义
于是我们需要如下运行 :
$ npx babel-node src/index.js
添加热加载
加入热加载,nodemon
$ npx nodemon --exec babel-node src/index.js
package.json 文件中修改配置
"scripts": {"start": " nodemon --exec babel-node src/index.js"}
之后运行: $ npm run start 就可以启动项目啦
