How to do ${opt:stage, "dev"} in a serverless.ts (js) file?

hi there,
just wondering if there are examples of full blown serverless.ts template files. on how to use/reference cli option and environment variables etc.
thanks for help!

2 Likes

Hi. I’ve noticed that the serverless.ts files are very new, so I don’t think there will be many examples. I have just tested your example though, and you can simply wrap it in quotes like this:

environment: {
test: "${opt:stage}"
}

Because it’s a ts file, you can also declare all your options in strings above the full object and then just reference them below, like this:

const myCustomStage = "dev";
const dbName = "mydatabase";

const serverlessConfiguration: Serverless = {
  provider: {
     stage: myCustomStage,
  },
};

You can test your config with the print command. This will interpret your config object and print it to the console.

sls print

7 Likes

Hi @alexvdvalk, thank your very much for your help and examples!

1 Like

Furthering if you are moving from the yml syntax and you make use of the custom section just as Alex has described you can do this sort of thing as well:

example custom section in the serverless.ts:

    custom: {
        cognito: {
            dev: {
                pool: 'us-east-1_HWLRunTyiU',
                client: 'Ap94PUjRJYALbRfjC5Q6Qr'
            },
            prod: {
                pool: 'us-east-1_66tqBehcL4x',
                client: 'Vy2qEgGb3H4yA6pKEf5F1r'
            },
.
.
.

You can access those variables just as Alex described with this:

environment: {
      AWS_NODEJS_CONNECTION_REUSE_ENABLED: '1',
      COGNITO_POOL: "${self:custom.cognito.${opt:stage}.pool}",
      COGNITO_CLIENT: "${self:custom.cognito.${opt:stage}.client}",
    },
6 Likes

I could not get “${env.DOMAIN_NAME}” ${env.DOMAIN_NAME} “${env.process.DOMAIN_NAME}” etc to work.

I could get env.process.DOMAIN to work by doing


import * as dotenv from "dotenv";
dotenv.config({path: __dirname + '/.env'});
domainName:  process.env.DOMAIN,

Even though I have useDotenv: true,