From 0ec1906e45e6956dee22469bcbccaca889b28eac Mon Sep 17 00:00:00 2001 From: Richard Heng Date: Wed, 16 May 2018 16:42:47 -0700 Subject: [PATCH] Adding support for unnamed imports. --- plugin/index.js | 31 ++++++++++++++++++------------- test/plugin.spec.js | 15 +++++++++++++++ 2 files changed, 33 insertions(+), 13 deletions(-) diff --git a/plugin/index.js b/plugin/index.js index e20d032..9087127 100644 --- a/plugin/index.js +++ b/plugin/index.js @@ -21,21 +21,26 @@ export default function({ types: t }) { reference = BabelInlineImportHelper.transformRelativeToRootPath(reference); } - const id = path.node.specifiers[0].local.name; const content = BabelInlineImportHelper.getContents(givenPath, reference); - const variable = t.variableDeclarator(t.identifier(id), t.stringLiteral(content)); + if (path.node.specifiers.length > 0) { + const id = path.node.specifiers[0].local.name; + const variable = t.variableDeclarator(t.identifier(id), t.stringLiteral(content)); - path.replaceWith({ - type: 'VariableDeclaration', - kind: 'const', - declarations: [variable], - leadingComments: [ - { - type: 'CommentBlock', - value: ` babel-plugin-inline-import '${givenPath}' ` - } - ] - }); + path.replaceWith({ + type: 'VariableDeclaration', + kind: 'const', + declarations: [variable], + leadingComments: [ + { + type: 'CommentBlock', + value: ` babel-plugin-inline-import '${givenPath}' ` + } + ] + }); + } else { + const literal = t.stringLiteral(content); + path.replaceWith(literal); + } } } } diff --git a/test/plugin.spec.js b/test/plugin.spec.js index 8591b7d..0b228c0 100644 --- a/test/plugin.spec.js +++ b/test/plugin.spec.js @@ -27,6 +27,21 @@ describe('Babel Inline Import - Plugin', () => { expect(transformedCode.code).to.equal(`/* babel-plugin-inline-import './fixtures/example.py' */var SomeExample = 'print 1 + 1\\n';`); }); + it('accepts unnamed imports', () => { + const transformedCode = babel.transform("import './fixtures/example.py';", { + filename: __filename, + plugins: [[ + BabelInlineImportPlugin, { + extensions: [ + '.py' + ] + } + ]] + }); + + expect(transformedCode.code).to.equal(`'print 1 + 1\\n';`); + }); + it('throws error when importing with destructuring', () => { expect(() => { babel.transform("import { SomeExample, AnotherExample } from './fixtures/example.raw';", {