Search code examples
javascriptreactjssingle-spaimport-maps

Use environment variable inside importmap - single-spa


I'm trying to use a environment variable inside the importmap that is used for single-spa configuration:

<% if (isLocal) { %>
  <script type="systemjs-importmap">
    {
      "imports": {
        "@polyglot-mf/root-config": "//localhost:9000/polyglot-mf-root-config.js"
      }
    }
  </script>
  <% } %>

But I want to manage the //localhost:9000/polyglot-mf-root-config.js inside an environment variable, so, I want something like:

   <% if (isLocal) { %>
  <script type="systemjs-importmap">
    {
      "imports": {
        "@polyglot-mf/root-config": process.env.URL_ROOT
      }
    }
  </script>
  <% } %>

I've tried to achieve this using process.env directly and declaring a variable before and using it inside the import:

<script type="systemjs-importmap">

    let urlRoot = process.env.URL_ROOT
  
    {
      "imports": {
        "@polyglot-mf/root-config"  : urlRoot ,
      }
    }
  </script>

But that doesn't work, this throws an error that process is not defined.

Any idea about how I can make it work?


Solution

  • What I did was send the environment variables when I start the microfrontend.

    So, my npm start script is:

    webpack serve --env isLocal --env URL_ROOT="//localhost:9000/polyglot-mf-root-config.js"
    

    Later, I have to modify my webpack.config.js for add the environment variable:

    return merge(defaultConfig, {
        // modify the webpack config however you'd like to by adding to this object
        plugins: [
          new HtmlWebpackPlugin({
            inject: false,
            template: "src/index.ejs",
            templateParameters: {
              isLocal: webpackConfigEnv && webpackConfigEnv.isLocal,
              URL_ROOT: webpackConfigEnv && webpackConfigEnv.URL_ROOT,
            }
          })
        ],
        externals: ["single-spa", "react", "react-dom", /^@SE\/.+$/]
      });
    

    And finally I can use the environment variable inside my .ejs file:

    <% if (isLocal) { %>
      <script type="systemjs-importmap">
        {
          "imports": {
            "@polyglot-mf/root-config": "<%= URL_ROOT %>"
          }
        }
      </script>
      <% } %>