Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Last active June 3, 2018 17:43
Show Gist options
  • Save sebinsua/e4cb303603409d0d7c624c24697d89a0 to your computer and use it in GitHub Desktop.
Save sebinsua/e4cb303603409d0d7c624c24697d89a0 to your computer and use it in GitHub Desktop.
Write named exports onto a path of a `package.json`
const { readFileSync, writeFileSync } = require('fs');
const writeNamedExportsToPathOfPkg = (output, path, namedExports) => {
if (!namedExports || namedExports.length === 0) {
return;
}
const pkgJson = JSON.parse(readFileSync(output, 'utf8'));
let level = pkgJson;
const p = path.split('.');
while (p.length) {
const el = p.shift();
level[el] = p.length ? level[el] || {} : namedExports;
level = level[el];
}
return writeFileSync(output, JSON.stringify(pkgJson, null, 2))
}
function writeNamedExports({
path,
output = './package.json'
}) {
if (!path) {
throw new Error(`The 'writeNamedExports' rollup plugin should be given a json path where it can place its named exports.`)
}
if (!output) {
throw new Error(`The 'writeNamedExports' rollup plugin should be given an 'output' path to write to.`)
}
return {
name: 'writeNamedExports',
onwrite(details) {
const namedExports = details.bundle.exports.filter(e => e !== 'default');
return writeNamedExportsToPathOfPkg(
output,
path,
namedExports
);
}
};
}
module.exports = {
input: 'src/index.js',
output: {
file: 'dist/index.esm.js',
format: 'es'
},
plugins: [ writeNamedExports({ path: 'appId.provides' }) ]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment