Last active
September 3, 2017 12:24
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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