rafgraph / spa-github-pages

Host single page apps with GitHub Pages
https://spa-github-pages.rafgraph.dev
MIT License
3.83k stars 565 forks source link

How to inject environmental variables into 404.html? #50

Closed serg06 closed 3 years ago

serg06 commented 3 years ago

I have an environmental variable PATH_SEGMENTS_TO_KEEP so I can deploy to different environments correctly. The only problem is I'm not sure how to inject it into 404.html. Is it possible?

rafgraph commented 3 years ago

I believe it’s possible, but I haven’t done it. You would need to set it up in your build tooling, which is out of scope for this project.

serg06 commented 3 years ago

I'll just add my solution here in case anyone needs it:

  1. npm run eject
  2. Add this to config/paths.js
app404Html: resolveApp('public/404.html'),
  1. In config/webpack.config.js, replace this
      // Generates an `index.html` file with the <script> injected.
      new HtmlWebpackPlugin(
        Object.assign(
          {},
          {
            inject: true,
            template: paths.appHtml,
          },
          isEnvProduction
            ? {
                minify: {
                  removeComments: true,
                  collapseWhitespace: true,
                  removeRedundantAttributes: true,
                  useShortDoctype: true,
                  removeEmptyAttributes: true,
                  removeStyleLinkTypeAttributes: true,
                  keepClosingSlash: true,
                  minifyJS: true,
                  minifyCSS: true,
                  minifyURLs: true,
                },
              }
            : undefined
        )
    ),

with this:

      ...[
        {
          // Generates an `index.html` file with the <script> injected.
          inject: true,
          template: paths.appHtml,
          filename: 'index.html'
        },
        {
          // Generates a `404.html` file.
          inject: false,
          template: paths.app404Html,
          filename: '404.html'
        }
      ].map(
        cfg => new HtmlWebpackPlugin(
            Object.assign(
              {},
              cfg,
              isEnvProduction
                ? {
                    minify: {
                      removeComments: true,
                      collapseWhitespace: true,
                      removeRedundantAttributes: true,
                      useShortDoctype: true,
                      removeEmptyAttributes: true,
                      removeStyleLinkTypeAttributes: true,
                      keepClosingSlash: true,
                      minifyJS: true,
                      minifyCSS: true,
                      minifyURLs: true,
                    },
                  }
                : undefined
            )
          )
      ),

Boom, environmental variables work in 404.html.

rafgraph commented 3 years ago

@serg06 thanks! Is this ejecting from create-react-app?

serg06 commented 3 years ago

@rafgraph Yes