Is it possible to set environmental variables in Figma plugin?

Is it possible to set non-sensitive environmental variables (like rootUrl) in the Figma plugin? So I don’t have to manually switch variables between my dev environment and production.

I haven’t tried but there are libraries for that: GitHub - zertosh/loose-envify: Like envify but much faster, google something like client-side env variables. javascript - Is it possible to use dotenv in a react project? - Stack Overflow

I found out a way to do this myself:
Figma uses WebPack to compile the code, and it uses HtmlWebpackPlugin, and this plugin allows us to pass extra information to ui.html.

// webpack.config.js
plugins: [
    new HtmlWebpackPlugin({
      template: "./src/ui.html",
      filename: "ui.html",
      inlineSource: ".(js)$",
      chunks: ["ui"],
      inject: "body",
      cache: false,
      // Below is the extra information that I want to pass to ui.html
      env: argv.mode === "production" ? "production" : "development",
    }),
  ],

Then we can access to this data in ui.html

// ui.html
const env = '<%= htmlWebpackPlugin.options.env %>'
const BASE_URL = env === "development" ? "http://localhost:8080" : "https://your-production-url.com"

If you are using Gulp, maybe this can help:
Read environment variables and then replace them in client-side JS when using gulp for building prod or dev code

If you are using ESBuild, maybe this can help:
https://esbuild.github.io/api/#define

1 Like