Parcel v2: how to use env file for dynamically importing dependencies at build time

98 Views Asked by At

I'm using Parcel v2 as the bundler for my project, in combination with the plugin for loading SCSS. Given that it is required for me to apply white labeling on the project (different colors and fonts for different brands on the same code base), I want to be able to apply different styling depending on a value in the .env file.

In my .env file, I have the following parameter

BRAND_ID=1

Relevant part of package.json

{
  "source": "src/index.js",
  "targets": {
    "default": {
      "distDir": "./dist"
    }
  },
  "browserslist": "> 0.2%, last 4 versions, not ie <= 10, not dead",
}

Then I have a folder with on one hand the common SCSS, and the brand-specific SCSS (simplified version):

src
├── scss
│   ├── brands
│   │   ├── 1
│   │   │   ├── colors.scss
│   │   │   └── fonts.scss
│   │   ├── 2
│   │   │   ├── colors.scss
│   │   │   └── fonts.scss
│   │   ├── 3
│   │   │   ├── colors.scss
│   │   │   └── fonts.scss
│   ├── components
│   │   ├── button.scss
│   │   └── call-to-action.scss
│   ├── index.js
│   └── main.scss
└── index.js

Now, given that the colors.scss and fonts.scss define SCSS variables, I want to be able to import them at build time, depending the BRAND_ID env parameter. . So at that moment, I want to bundle main.scss , brands/BRAND_ID/*.scss and components/*.scss into one index.css file

The problem is two-fold

  • I'm not sure how to read the env variables at build time. How I understood the docs is that parcel would inject the variables during build time, but I could not figure out how to actually access them to and to use them in order to apply build logic.
  • Give that I would have the variables form the previous point, I can't seem to find a way to conditionally import certain files. I tried the import() method, but that seems to be created for code splitting in order to dynamically load contents at run time, which does not fit my case

How should I proceed to achieve this?

0

There are 0 best solutions below