Giter Site home page Giter Site logo

nest-sls-webpack-template's Introduction

Nest Logo

A progressive Node.js framework for building efficient and scalable server-side applications.

NPM Version Package License NPM Downloads CircleCI Coverage Discord Backers on Open Collective Sponsors on Open Collective Support us

Description

Nest framework TypeScript starter repository.

Configurations

1. Install Packages

yarn add @codegenie/serverless-express aws-lambda @nestjs/config
yarn add -D @types/aws-lambda serverless-offline serverless-webpack terser-webpack-plugin fork-ts-checker-webpack-plugin

2. Add Serverless.yml

# replace app-name
service: app-name
frameworkVersion: '3'

plugins:
  - serverless-webpack
  - serverless-offline

custom:
  config: ${file(./config/${self:provider.stage}.env.json)}
  webpack:
    includeModules: true
    forceExclude:
      - aws-sdk

provider:
  name: aws
  deploymentMethod: direct
  runtime: nodejs20.x
  stage: ${opt:stage, 'dev'}
  region: ${opt:region, 'ap-southeast-1'}
  environment: ${file(./config/${opt:stage, 'dev'}.env.json)}
  # adjust bucket & vpc as needed
  # deploymentBucket:
  #   name: bucket_name
  # vpc:
  #   securityGroupIds:
  #     - sg-xxx
  #   subnetIds:
  #     - subnet-xxx
  #     - subnet-xxx
  #     - subnet-xxx

functions:
  api:
    handler: dist/main.handler
    # adjust memory, storage, and timeout as needed.
    # memorySize: 2048
    # ephemeralStorageSize: 1024
    # timeout: 25
    events:
      - httpApi: '*'

3. Update app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from '@nestjs/config';

@Module({
  // add config module to fetch env
  imports: [ConfigModule.forRoot({ isGlobal: true })],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

4. Update main.ts

import { NestFactory } from '@nestjs/core';
import serverlessExpress from '@codegenie/serverless-express';
import { Callback, Context, Handler } from 'aws-lambda';
import { AppModule } from './app.module';

let server: Handler;

async function bootstrapSLS(): Promise<Handler> {
  const app = await NestFactory.create(AppModule);
  await app.init();

  const expressApp = app.getHttpAdapter().getInstance();
  return serverlessExpress({ app: expressApp });
}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}

export const handler: Handler = async (
  event: any,
  context: Context,
  callback: Callback,
) => {
  server = server ?? (await bootstrapSLS());
  return server(event, context, callback);
};

if (process.env.NEST_ENV === 'HTTP') {
  bootstrap();
}

5. Update tsconfig.json

{
  "compilerOptions": {
    ...
    "esModuleInterop": true
  }
}

6. Add webpack.config.js

/* eslint-disable @typescript-eslint/no-var-requires */
const webpack = require('webpack');
const path = require('path');
const slsw = require('serverless-webpack');
const TerserPlugin = require('terser-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');

const lazyImports = [
  '@nestjs/microservices',
  '@nestjs/microservices/microservices-module',
  '@nestjs/websockets/socket-module',
  '@nestjs/platform-express',
  '@grpc/grpc-js',
  '@grpc/proto-loader',
  'kafkajs',
  'mqtt',
  'nats',
  'ioredis',
  'amqplib',
  'amqp-connection-manager',
  'pg-native',
  'cache-manager',
  'class-validator',
  'class-transformer',
];

module.exports = {
  mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
  devtool: 'source-map',
  entry: slsw.lib.entries,
  target: 'node',
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  output: {
    libraryTarget: 'commonjs2',
    path: path.join(__dirname, '.webpack'),
    filename: '[name].js',
  },
  externals: {
    // add package to be excluded in bundle, example:
    // argon2: 'commonjs argon2',
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        loader: 'ts-loader',
        options: {
          // disable type checker - we will use it in fork plugin
          transpileOnly: true,
        },
      },
    ],
  },
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          keep_classnames: true,
        },
      }),
    ],
  },
  plugins: [
    new ForkTsCheckerWebpackPlugin(),
    new webpack.IgnorePlugin({
      checkResource(resource) {
        if (lazyImports.includes(resource)) {
          try {
            require.resolve(resource);
          } catch (err) {
            return true;
          }
        }
        return false;
      },
    }),
  ],
};

7. Update .gitignore

.serverless
.webpack

.env*
*.env.json

8. Add env file

config/
┣ dev.env.json
┗ prod.env.json

9. Update package.json scripts

{
  "start:sls": "nest build && serverless offline start",
  "deploy:dev": "nest build && serverless deploy -s dev",
  "deploy:prod": "nest build && serverless deploy -s prod"
}

Running the app

You can run the app either by serverless offline or normal server.

serverless offline
yarn start:sls
normal server

Make sure to add this value to .env file

NEST_ENV = "HTTP"

then run

yarn start:dev

Deploying the app

yarn deploy:dev

Reference

nest-sls-webpack-template's People

Contributors

syazwanz avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.