Skip to content

Instantly share code, notes, and snippets.

@koganei
Created March 17, 2023 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koganei/bb64258bda3a0219612cc40f375441be to your computer and use it in GitHub Desktop.
Save koganei/bb64258bda3a0219612cc40f375441be to your computer and use it in GitHub Desktop.
ChatGPT generation of an import map tool

USER

Hi, can you give me the javascript code that will generate an import map for a given package.json so that code works in web browsers without any kind of building?

ASSISTANT

Certainly! Below is a JavaScript code snippet that generates an import map for a given package.json file. This code assumes that the dependencies in the package.json are already downloaded and placed in a folder named node_modules within your project directory, and it generates an import map compatible with native ES modules in web browsers without requiring a build step.

const fs = require("fs");

function generateImportMap(packageJsonPath) {
  const packageJsonContent = fs.readFileSync(packageJsonPath, "utf-8");
  const packageJson = JSON.parse(packageJsonContent);

  if (!packageJson.dependencies) {
    console.error("No dependencies found in package.json");
    return;
  }

  const importMap = {
    imports: {},
  };

  for (const [packageName, packageVersion] of Object.entries(packageJson.dependencies)) {
    const packagePath = `./node_modules/${packageName}/package.json`;
    const packageContent = fs.readFileSync(packagePath, "utf-8");
    const packageData = JSON.parse(packageContent);

    if (!packageData.module) {
      console.error(`The package ${packageName} does not have a module entry.`);
      continue;
    }

    const modulePath = `./node_modules/${packageName}/${packageData.module}`;
    importMap.imports[packageName] = modulePath;
  }

  fs.writeFileSync("import-map.json", JSON.stringify(importMap, null, 2), "utf-8");
  console.log("Import map has been generated: import-map.json");
}

// Replace the path below with the path to your package.json file
generateImportMap("./path/to/your/package.json");

To use this script, create a file named generate-import-map.js in your project directory and paste the code above into the file. Replace ./path/to/your/package.json with the path to your package.json file. Then, run the script using Node.js:

node generate-import-map.js

The script will generate an import-map.json file in the project directory. To use the import map in your HTML file, add the following code within the <head> tag:

<script type="importmap" src="import-map.json"></script>

Now, you can use the native ES modules in your JavaScript code, importing packages directly from your node_modules folder:

import { functionName } from "package-name";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment