Skip to content

Instantly share code, notes, and snippets.

@qubyte
Last active September 3, 2017 12:24
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 qubyte/328a26e148f53c2f91071015ce8b2cab to your computer and use it in GitHub Desktop.
Save qubyte/328a26e148f53c2f91071015ce8b2cab to your computer and use it in GitHub Desktop.
rollup plugin for wrapping a JSON file in a module with a default export only. This avoids the issue of fields being invalid names.
// An as-simple-as-possible JSON plugin for rollup. This plugin turns a JSON
// file into a module with a default export. No named exports are given since
// field names are not always valid names.
// Originally drawn from the official JSON plugin.
function buildAst(code) {
return {
type: 'Program',
sourceType: 'module',
start: 0,
end: code.length,
body: [
{
type: 'ExportDefaultDeclaration',
start: 0,
end: code.length,
declaration: {
type: 'Literal',
start: 15,
end: code.length - 1,
value: null,
raw: 'null'
}
}
]
};
}
function transform(untrimmed, id) {
if (!id.endsWith('.json')) {
return null;
}
// Trim leading and trailing whitespace.
const json = untrimmed.replace(/^\s+|\s+$/g, '');
// Ensure JSON parses.
JSON.parse(json);
const code = `export default ${json};`;
const ast = buildAst(code);
return { ast, code, map: { mappings: '' } };
}
module.exports = function json() {
return { name: 'json', transform };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment