Skip to content
New issue

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

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

Already on GitHub? # to your account

Cannot be used as dynamic import #11

Open
JonathanCabezas opened this issue Aug 20, 2024 · 0 comments
Open

Cannot be used as dynamic import #11

JonathanCabezas opened this issue Aug 20, 2024 · 0 comments

Comments

@JonathanCabezas
Copy link

JonathanCabezas commented Aug 20, 2024

I did a custom script that you can use as npm pre-start hook that will run expose-wsl every time Windows has been rebooted:

import { exec } from "child_process";
import { readFile, writeFile } from "fs/promises";
import { promisify } from "util";

const bootTimeFile = new URL("last-windows-boot-time.txt", import.meta.url).pathname;

try {
  const { stdout: bootTime, stderr } = await promisify(exec)(
    "wmic.exe os get lastbootuptime | sed -n 2p"
  );
  if (stderr !== "") {
    throw new Error(stderr);
  }

  let lastBootTime = "";
  try {
    lastBootTime = await readFile(bootTimeFile, "utf-8");
  } catch (_) {
    // File does not exist
  }

  if (bootTime !== lastBootTime) {
    // We are on WSL and Windows has been rebooted
    // We can execute expose-wsl
    console.log("Windows has been rebooted");
    await writeFile(bootTimeFile, bootTime);
    await import("expose-wsl"); // expose-wsl ends with process.exit so we need to end with it
  }
} catch (_) {
  // WSL is not running
}

It works great but I'd prefer to first import expose-wsl and then write the bootTimeFile, but I can't since expose-wsl ends with process.exit.

If you want to use your package both as an entrypoint and as a module, you should encapsulate all your processing logic into a function which throws error (success true by default instead of success false by default as you do).

Then if you are in main (you can use the package es-main to check this), you can catch any error and do process.exit(1):

import esMain from 'es-main';

if (esMain(import.meta)) {
  try {
    await exposeWsl();
  } catch (error) {
    console.error(error);
    process.exit(1);
  }
}
@JonathanCabezas JonathanCabezas changed the title Use as dynamic import Cannot be used as dynamic import Aug 20, 2024
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant