Parse composer.json file

Use a composer.json file from a Drupal project to check which modules are installed.

Since it's a json file, we can just read the data in a script and get data from the object.

import composerJson from "../data/composer.json" assert {type: 'json'};

This code above uses import assertions: https://v8.dev/features/import-assertions

const extensions = { require: new Set(), 'require-dev': new Set()};

['require', 'require-dev'].forEach(item => {
    for (const extension in composerJson[item]) {
        const extensionParts = extension.split('/');
        const nameSpace = extensionParts[0];
        const extensionName = extensionParts[1];
        if (nameSpace == 'drupal') {
            extensions[item].add(extensionName);
        }
    }
})

export default extensions;

This loops through the two extensions lists (dev/non-dev) and returns an object of all that start with drupal/, keyed by require or require-dev.

When this code is bundled, the content of the json file is exported with the script, so no external calls to the file are needed.

Topics