Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Live Reload still loading when splitting is true and format is esm #3695

Closed
gusma296 opened this issue Mar 13, 2024 · 1 comment
Closed

Live Reload still loading when splitting is true and format is esm #3695

gusma296 opened this issue Mar 13, 2024 · 1 comment

Comments

@gusma296
Copy link

gusma296 commented Mar 13, 2024

im trying to mode splitting true but when live reload web still loading.

import { htmlPlugin } from "@craftamap/esbuild-plugin-html";
import * as esbuild from 'esbuild';
import clean from "esbuild-plugin-clean";
import copy from "esbuild-plugin-copy";
import { postcssModules, sassPlugin } from "esbuild-sass-plugin";
import fs from 'fs';
import http from "http";
import open from "open";
import path from 'path';
import url from 'postcss-url';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const args = process.argv.slice(2)
const watch = args.includes('--watch')
const PORT = process.env.PORT;

const watchPlugin = {
  name: 'watch-plugin',
  setup(build) {
    build.onStart(()=>{console.log(`Build Starting: ${new Date(Date.now()).toLocaleTimeString()}`)})
    build.onEnd((result)=> {
      if (result.errors.length > 0) {
        console.log(`Build Finished, with errors: ${new Date(Date.now()).toLocaleTimeString()}`);
      }else{
        console.log(`Build Finished: ${new Date(Date.now()).toLocaleTimeString()}`);
      }
    })
  }
}

function proxy (host = '0.0.0.0', port = 8000) {
  return http.createServer(proxy);

  function proxy(req, res) {
      const forwardRequest = (path) => {
          const options = {
              hostname: host,
              port,
              path,
              method: req.method,
              headers: req.headers,
          };
          const proxyReq = http.request(options, (proxyRes) => {
              if (proxyRes.statusCode === 404) {
                  return forwardRequest("/");
              }
              res.writeHead(proxyRes.statusCode, proxyRes.headers);
              proxyRes.pipe(res, { end: true });
          });

          req.pipe(proxyReq, { end: true });
      };
      forwardRequest(req.url);
  }
}

const define = {
	"process.env.NODE_ENV": `"${process.env.REACT_APP_HOST_ENV}"`,
};

for (const k in process.env) {
	if (k.startsWith("REACT_APP_") || ["BUILD_VERSION"].includes(k)) {
		define[`process.env.${k}`] = JSON.stringify(process.env[k]);
	}
}

const context = await esbuild.context({
    entryPoints: ["src/index.tsx"],
    bundle: true,
    minify: true,
    splitting: true,
    format: "esm",
    treeShaking: true,
    sourcemap: "external",
    outdir: __dirname + "/build-es/",
    metafile: true,
    publicPath: "/",
    loader: {
        ".js": "jsx",
        ".svg": "dataurl",
        ".scss": "css",
        ".png": "dataurl",
        ".jpg": "dataurl"
    },
    define,
    target: ["chrome58", "firefox57", "safari11", "edge18"],
    supported: {
        "import-meta": true, // Due to JOIToi being used rather than mobx. Developers need to fix this
    },
    assetNames: "assets/[name]-[hash]",
    banner: {
      js: "(() => { (new EventSource(\"/esbuild\")).addEventListener('change', () => location.reload()); })();"
    },
    write: true,
    plugins: [
        watchPlugin,
        clean({
            patterns: ["./build-es/*", "./build-es/assets/*"],
        }),
        copy({
            resolveFrom: "cwd",
            assets: [
                {
                    from: ["public/**/*"],
                    to: ["build-es"],
                    keepStructure: true,
                },
            ],
        }),
        copy({
          resolveFrom: "cwd",
          assets: [
              {
                  from: ["public/.well-known/*"],
                  to: ["build-es/.well-known"],
                  keepStructure: true,
              },
          ],
      }),
        htmlPlugin({
            files: [
                {
                    entryPoints: ["src/index.tsx"],
                    filename: "index.html",
                    scriptLoading: 'module',
                    htmlTemplate: fs
                        .readFileSync("public/index.html")
                        .toString()
                        .replace(/%PUBLIC_URL%/g, process.env.REACT_APP_HOST_ENV || ""),
                },
            ],
        }),
        sassPlugin({
            type: "css",
            loadPaths: [__dirname, __dirname + "src"],
            filter: /\.module\.scss$/,
				// Need to figure out how to conbine the postCssModules and this
				// https://github.com/glromeo/esbuild-sass-plugin/issues/92#issuecomment-1219209442
				transform: postcssModules({
					root: __dirname
					// ...put here the options for postcss-modules: https://github.com/madyankin/postcss-modules
				},[url({ url: 'inline'})]),
        }),
        sassPlugin({
            type: "css",
            loadPaths: [__dirname, __dirname + "src"]
        }),
    ],
})

if (watch) {
    await context.watch();
    await context.serve({
      servedir:__dirname +'/build-es/',
    }).then(()=>{
        proxy().listen(PORT,()=>{
          open(`http://localhost:${PORT}/`)
      })
    })
  }else{
    await context.rebuild();
    context.dispose();
  }
@gusma296 gusma296 closed this as completed May 6, 2024
@gusma296 gusma296 reopened this May 6, 2024
@gusma296
Copy link
Author

gusma296 commented May 6, 2024

move new EventSource(\"/esbuild\")).addEventListener('change', () => location.reload() to index.html from banner

@gusma296 gusma296 closed this as completed May 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant