Search code examples
rollupjs

Get Rollup static path for json5 file like react-create-app does it


I have created an app using react-create-app. When I import a .json5 file, it treats it as a static file, copies it to build/dist folder, and returns its relative path:

import foo from './some-file.json5'

console.log(foo); // logs: /static/media/some-file.hash.json5

Then I can easily fetch this file when I serve my app.

How I can to the same thing using rollup and its plugins?


Solution

  • I just wrote my own plugin for this, enjoy:

    import path from "path";
    import fs from "fs";
    
    export default function copyAndExportPath() {
      return {
        name: "copy-and-export-path",
        resolveId(source, importer) {
          if (source.endsWith(".json5")) {
            const absolutePath = path.resolve(path.dirname(importer), source);
    
            return absolutePath;
          }
        },
    
        load(id, importer) {
          if (id.endsWith(".json5")) {
            const [base, dest] = id.split("src");
            const absolutePathDest = path.join(base, "dist", dest);
    
            const destDir = path.dirname(absolutePathDest);
    
            if (!fs.existsSync(destDir)) {
              fs.mkdirSync(destDir, { recursive: true }, (error) => {
                if (error) {
                  throw error;
                }
              });
            }
    
            if (fs.existsSync(destDir)) {
              fs.copyFileSync(id, absolutePathDest);
            }
    
            return `export default ".${dest}"`;
          }
          return null;
        },
      };
    }