1

I want to define environment variables in my package.json where I'm using Snowpack, but as far as I know Snowpack sets the NODE_ENV automatically based on dev vs build.

Is it possible to define variables for 3 modes instead of 2, I mean:

  • development
  • preproduction
  • production

These are my scripts in my package.json:

"scripts": {
    "start": "snowpack dev",
    "build": "snowpack build NODE_ENV=pre",
    "build:production": "snowpack build NODE_ENV=pro"
}

However, import.meta.env.MODE returns production for the 2 types of build.

I couldn't make it work, maybe there is another way of doing this.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Johnny Johnny
  • 319
  • 2
  • 11

1 Answers1

1

My use case was not exactly the same, but similar, and you should be able to generate as many different environments as you want with this technique.

I was able to do this by writing a custom snowpack plugin to use .env files with the dotenv npm package, and two separate snowpack.config.js files; one for dev and one for prod. Here's how...

  1. Add dotenv to your project: npm i -D dotenv
  2. Create this new file. This will be our custom snowpack plugin
// env-loader.js
const dotenv = require('dotenv');
module.exports = function plugin(snowpackConfig, { path }) {
  dotenv.config({ path: path });
  return { name: 'Custom plugin from StackOverflow' };
};

  1. Create your .env files; .env.develop and .env.production
  2. Create your snowpack.config files; snowpack-develop.config.js and snowpack-production.config.js
  3. Add your custom plugin to both snowpack.config files. Be sure to give it the correct path to your custom plugin, and the correct path to your .env files.
// snowpack-develop.config.js
const path = require('path'); 
module.exports = {
  plugins: [
    ['./path/to/env-loader', { path: path.resolve(process.cwd(), '.develop.env') }],
  ],
};

  1. Finally, add your npm scripts. Point your dev scripts to the snowpack-develop file, and prod to the snowpack-production file.
  "scripts": {
    "develop": "snowpack dev --config ./snowpack-develop.config.js",
    "build:dev": "snowpack build --config ./snowpack-develop.config.js",
    "build:prod": "snowpack build --config ./snowpack-production.config.js"
  },

In snowpack, environment variables must include the prefix SNOWPACK_PUBLIC_, and to use a variable in your code you would access it like this: import.meta.env.SNOWPACK_PUBLIC_MY_VARIABLE. It runs a find-and-replace at build time.

Snowpack Config Docs
Snowpack Plugin Docs
Snowpack Env Docs

TJBlackman
  • 1,895
  • 3
  • 20
  • 46