安装与配置 #

一、环境准备 #

1.1 安装Node.js #

Hapi.js需要Node.js 12.x或更高版本。

检查Node.js版本:

bash
node --version

推荐使用LTS版本:

bash
# 使用nvm安装
nvm install --lts
nvm use --lts

1.2 安装npm或yarn #

bash
# 检查npm版本
npm --version

# 或安装yarn
npm install -g yarn
yarn --version

二、创建项目 #

2.1 初始化项目 #

bash
# 创建项目目录
mkdir my-hapi-app
cd my-hapi-app

# 初始化package.json
npm init -y

2.2 安装Hapi #

bash
# 使用npm
npm install @hapi/hapi

# 或使用yarn
yarn add @hapi/hapi

2.3 安装常用依赖 #

bash
# 数据验证
npm install @hapi/joi

# HTTP错误处理
npm install @hapi/boom

# 静态文件服务
npm install @hapi/inert

# 模板引擎支持
npm install @hapi/vision

# 开发热重载
npm install -D nodemon

三、项目结构 #

3.1 基础结构 #

text
my-hapi-app/
├── src/
│   ├── index.js          # 入口文件
│   ├── config/           # 配置文件
│   │   └── index.js
│   ├── routes/           # 路由定义
│   │   └── index.js
│   ├── plugins/          # 插件
│   │   └── index.js
│   └── handlers/         # 处理函数
│       └── users.js
├── package.json
└── .env                  # 环境变量

3.2 创建基础文件 #

src/index.js:

javascript
const Hapi = require('@hapi/hapi');
const routes = require('./routes');

const init = async () => {
    const server = Hapi.server({
        port: process.env.PORT || 3000,
        host: 'localhost'
    });

    server.route(routes);

    await server.start();
    console.log('Server running on %s', server.info.uri);
};

process.on('unhandledRejection', (err) => {
    console.log(err);
    process.exit(1);
});

init();

src/routes/index.js:

javascript
module.exports = [
    {
        method: 'GET',
        path: '/',
        handler: (request, h) => {
            return { message: 'Welcome to Hapi!' };
        }
    },
    {
        method: 'GET',
        path: '/health',
        handler: (request, h) => {
            return { status: 'ok' };
        }
    }
];

四、配置管理 #

4.1 环境变量 #

安装dotenv:

bash
npm install dotenv

创建.env文件:

env
PORT=3000
HOST=localhost
NODE_ENV=development

使用环境变量:

javascript
require('dotenv').config();

const server = Hapi.server({
    port: process.env.PORT || 3000,
    host: process.env.HOST || 'localhost'
});

4.2 配置文件 #

src/config/index.js:

javascript
const config = {
    development: {
        port: 3000,
        host: 'localhost',
        database: {
            host: 'localhost',
            port: 5432,
            name: 'myapp_dev'
        }
    },
    production: {
        port: process.env.PORT || 8080,
        host: '0.0.0.0',
        database: {
            host: process.env.DB_HOST,
            port: process.env.DB_PORT,
            name: process.env.DB_NAME
        }
    }
};

const env = process.env.NODE_ENV || 'development';

module.exports = config[env];

使用配置:

javascript
const config = require('./config');

const server = Hapi.server({
    port: config.port,
    host: config.host
});

五、开发工具 #

5.1 Nodemon配置 #

package.json:

json
{
    "scripts": {
        "start": "node src/index.js",
        "dev": "nodemon src/index.js"
    }
}

nodemon.json:

json
{
    "watch": ["src"],
    "ext": "js,json",
    "ignore": ["src/**/*.spec.js"]
}

5.2 ESLint配置 #

bash
npm install -D eslint
npx eslint --init

.eslintrc.js:

javascript
module.exports = {
    env: {
        node: true,
        es2021: true
    },
    extends: 'eslint:recommended',
    parserOptions: {
        ecmaVersion: 'latest',
        sourceType: 'module'
    },
    rules: {
        'no-unused-vars': 'warn',
        'no-console': 'off'
    }
};

5.3 VS Code配置 #

.vscode/launch.json:

json
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "skipFiles": ["<node_internals>/**"],
            "program": "${workspaceFolder}/src/index.js",
            "envFile": "${workspaceFolder}/.env"
        }
    ]
}

六、TypeScript支持 #

6.1 安装TypeScript #

bash
npm install -D typescript @types/node ts-node
npx tsc --init

6.2 TypeScript配置 #

tsconfig.json:

json
{
    "compilerOptions": {
        "target": "ES2020",
        "module": "commonjs",
        "lib": ["ES2020"],
        "outDir": "./dist",
        "rootDir": "./src",
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true
    },
    "include": ["src/**/*"],
    "exclude": ["node_modules"]
}

6.3 TypeScript示例 #

src/index.ts:

typescript
import Hapi from '@hapi/hapi';

const init = async (): Promise<void> => {
    const server = Hapi.server({
        port: 3000,
        host: 'localhost'
    });

    server.route({
        method: 'GET',
        path: '/',
        handler: (request, h) => {
            return { message: 'Hello TypeScript!' };
        }
    });

    await server.start();
    console.log('Server running on %s', server.info.uri);
};

init();

七、启动项目 #

7.1 开发模式 #

bash
npm run dev

7.2 生产模式 #

bash
npm start

7.3 验证安装 #

访问 http://localhost:3000 应该看到:

json
{
    "message": "Welcome to Hapi!"
}

八、常见问题 #

8.1 端口被占用 #

bash
# 查找占用端口的进程
lsof -i :3000

# 终止进程
kill -9 <PID>

8.2 模块找不到 #

bash
# 重新安装依赖
rm -rf node_modules
npm install

8.3 环境变量不生效 #

确保在代码最顶部加载dotenv:

javascript
require('dotenv').config();
// 其他代码...

九、总结 #

安装配置要点:

步骤 说明
环境准备 安装Node.js和npm
创建项目 npm init初始化
安装Hapi npm install @hapi/hapi
配置管理 使用环境变量和配置文件
开发工具 Nodemon、ESLint、TypeScript

下一步,让我们创建第一个Hapi应用!

最后更新:2026-03-28