Koa + ES6 + webpack 配置热加载

Koa + ES6 + webpack 配置热加载_第1张图片
简介

Koa 是一个新的 web 框架,由 Express 幕后的原班人马打造,
致力于成为 web 应用和 API 开发领域中的一个更小、
更富有表现力、更健壮的基石。通过利用 async 函数,
Koa 帮你丢弃回调函数,并有力地增强错误处理。
Koa 并没有捆绑任何中间件, 而是提供了一套优雅的方法,
帮助您快速而愉快地编写服务端应用程序。
但是koa本身用的是commonJS规范,不适用于流行的ES6规范 ,
在本文中给大家带来koa中使用ES6规范 以及配合 webpack实现热加载

package.json如下

{
    "name": "koa-2",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "nodemon --exec babel-node src/index.js"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
        "@koa/router": "^9.0.1",
        "koa": "^2.13.0",
        "koa-combine-routers": "^4.0.2",
        "koa-helmet": "^5.2.0",
        "koa-static": "^5.0.0"
    },
    "devDependencies": {
        "@babel/core": "^7.10.3",
        "@babel/node": "^7.10.3",
        "@babel/preset-env": "^7.10.3",
        "babel-loader": "^8.1.0",
        "clean-webpack-plugin": "^3.0.0",
        "cross-env": "^7.0.2",
        "nodemon": "^2.0.4",
        "webpack": "^4.43.0",
        "webpack-cli": "^3.3.12",
        "webpack-node-externals": "^1.7.2"
    }
}

.babelrc内容如下

{
    "presets": [
        [
            "@babel/preset-env",
            {
                "targets": {
                    "node": "current"
                }
            }
        ]
    ]
}

webpackconfig配置内容如下

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)$/,
            use: {
                loader: "babel-loader"
            },
            exclude: [path.join(__dirname, '/node_modules')]
        }]
    },
    externals: [nodeExternals()],
    plugins: [new CleanWebpackPlugin()],
    node: {
        console: true,
        global: true,
        process: true,
        Buffer: true,
        __filename: true,
        __dirname: true,
        setImmediate: true,
        path: true
    }
}
module.exports = webPackConfig

在项目中使用ES6语法如下所示

import koa from 'koa';

import path from 'path';

import statics from 'koa-static';

import helmet from 'koa-helmet';

import router from './route/routes';

const app = new koa();

app.use(helmet()); //启用安全帽

app.use(statics(path.join(__dirname, './public'))) //拼接路径

app.use(router()); //启用路由

app.listen(3000); //监听端口

就为大家介绍到这里了 谢谢观看

你可能感兴趣的:(nodeJS,node.js,es6/es7,webpack)