babel-plugin-inline-json-import
Advanced tools
Comparing version 0.1.6 to 0.2.0
@@ -29,4 +29,4 @@ 'use strict'; | ||
if (moduleName.match(/\.json$/)) { | ||
var variableName = node.specifiers[0].local.name; | ||
if (moduleName.match(/\.json(!json)?$/)) { | ||
var leftExpression = determineLeftExpression(t, node); | ||
@@ -42,5 +42,9 @@ var fileLocation = state.file.opts.filename; | ||
if (filepath.slice(-5) === '!json') { | ||
filepath = filepath.slice(0, filepath.length - 5); | ||
} | ||
var json = requireFresh(filepath); | ||
path.replaceWith(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(variableName), t.valueToNode(json))])); | ||
path.replaceWith(t.variableDeclaration('const', [t.variableDeclarator(leftExpression, t.valueToNode(json))])); | ||
} | ||
@@ -52,2 +56,27 @@ } | ||
function determineLeftExpression(types, node) { | ||
if (isDestructuredImportExpression(node)) { | ||
return buildObjectPatternFromDestructuredImport(types, node); | ||
} | ||
var variableName = node.specifiers[0].local.name; | ||
return types.identifier(variableName); | ||
} | ||
function isDestructuredImportExpression(node) { | ||
return node.specifiers.length !== 1 || node.specifiers[0].type !== 'ImportDefaultSpecifier'; | ||
} | ||
function buildObjectPatternFromDestructuredImport(types, node) { | ||
var properties = node.specifiers.map(function (specifier) { | ||
var key = types.identifier(specifier.imported.name); | ||
var value = types.identifier(specifier.local.name); | ||
return types.objectProperty(key, value); | ||
}); | ||
return types.objectPattern(properties); | ||
} | ||
function requireFresh(filepath) { | ||
@@ -54,0 +83,0 @@ (0, _decache2.default)(filepath); |
{ | ||
"name": "babel-plugin-inline-json-import", | ||
"version": "0.1.6", | ||
"version": "0.2.0", | ||
"description": "Inlines JSON file imports straight into JS code", | ||
@@ -5,0 +5,0 @@ "main": "build/index.js", |
@@ -25,2 +25,32 @@ import fs from 'fs' | ||
it('inlines simple systemjs JSON imports', () => { | ||
const t = configureTransform() | ||
const result = t(` | ||
import json from '../test/fixtures/example.json!json' | ||
console.log(json) | ||
`) | ||
expect(normalize(result.code)).to.equal(normalize(` | ||
const json = { example: true } | ||
console.log(json) | ||
`)) | ||
}) | ||
it('supports destructuring of the JSON imports', () => { | ||
const t = configureTransform() | ||
const result = t(` | ||
import {example} from '../test/fixtures/example.json' | ||
console.log(example) | ||
`) | ||
expect(normalize(result.code)).to.equal(normalize(` | ||
const { example: example } = { example: true } | ||
console.log(example) | ||
`)) | ||
}) | ||
it('does not inline other kinds of imports', () => { | ||
@@ -27,0 +57,0 @@ const t = configureTransform() |
14031
150