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...
- Add
dotenv
to your project: npm i -D dotenv
- 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' };
};
- Create your .env files;
.env.develop
and .env.production
- Create your snowpack.config files;
snowpack-develop.config.js
and snowpack-production.config.js
- 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') }],
],
};
- 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