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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

require of _package.json_ complicates bundling #455

Open
thescientist13 opened this issue Mar 27, 2023 · 0 comments
Open

require of _package.json_ complicates bundling #455

thescientist13 opened this issue Mar 27, 2023 · 0 comments

Comments

@thescientist13
Copy link

thescientist13 commented Mar 27, 2023

Hello! 馃憢

Was hoping to get your thoughts on an observation I had with a particular line in the project. Specifically where package.json is getting referenced via a require call.

exports.version = require('./package.json').version;

In the context of a project I am working on, a capability I am looking to achieve is being able to support running code in serverless environments, and so in those cases it is pretty common to bundle all the needed code into a "fat" lambda, so a single bundle.js artifact can be generated and uploaded to any cloud function service.

As this generally implies bundling of some sort to generate the single output file, the inclusion of a .json file complicates this a bit. I am using Rollup and so it requires a plugin / custom transform to convert the file into something Rollup can understand, like an ESM module.

function jsonLoader() {
  return {
    name: 'json-loader',
    async load(id) {
      const extension = id.split('.').pop();

      if (extension === 'json') {
        const url = new URL(`file://${id}`);
        const json = JSON.parse(await fs.promises.readFile(url, 'utf-8'));
        const contents = `export default ${JSON.stringify(json)}`;

        return contents;
      }
    }
  };
}

I can see from the code the value of bundling this to get a reference to the version from package.json. Would the project be open to alternate ways to handle this? Maybe something like below?

# Node >= 18 w/ ESM
import packageJson from './package.json' assert { type: 'json' };

# Node < 18
const packageJson = JSON.parse(await fs.promises.readFile('./package.json'));

exports.version = packageJson.version;

Thanks in advance for any consideration on this, and thank you so much for all the great work on this project! 馃檶


This may also be helpful to (or solved by?) related efforts and requests like #345 or #397 ?

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