fastify项目创建到打包(详细过程)

625 阅读1分钟

1.进行项目的创建

npm install fastify

2.默认生成下方文件

​编辑

3.在项目根目录新建server.js

​编辑

4.添加基本配置

npm i @fastify/cors


// CommonJs
const fastify = require('fastify')({
  logger: true,
})

//采用https的方式进行访问
// const fs = require('node:fs')
// const path = require('node:path')

// const fastify = require('fastify')({
//   logger: true,
//   http2: true,
//   https: {
//     key: fs.readFileSync(path.join(__dirname, 'cert.key')),
//     cert: fs.readFileSync(path.join(__dirname, 'cert.crt'))
//   },
// })

fastify.get('/', async (request, reply) => {
    return { hello: '111' }
  })
  fastify.register(require('@fastify/cors'), {
    origin: "*"
    // put your options here
  })
  
/**
 * Run the server!
 */
const start = async () => {
  try {
    await fastify.listen({ port: 3006, host: 'localhost' })
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

5.项目运行

node server.js

​编辑

6.安装nodemon

npm i nodemon

7.package.json中进行配置

​编辑

8.执行 npm run dev 进行项目运行

9.项目打包 

安装webpack,新建webpack.config.js

npm i webpack
npm install -D webpack-cli

const path = require('path');

module.exports = {
    entry: './server.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    target: 'node', // 这是最关键的
    mode: 'production',
};

配置

​编辑

执行npm run build进行打包

生成dist目录,在此目录下运行

node ./bundle.js

​编辑

​编辑