Skip to content
58 changes: 58 additions & 0 deletions packages/babel-plugin-named-asset-import/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,64 @@ function namedAssetImportPlugin({ types: t }) {

return {
visitor: {
ExportNamedDeclaration(
path,
{
opts: { loaderMap },
}
) {
if (!path.node.source) {
return;
}

const sourcePath = path.node.source.value;
const ext = extname(sourcePath).substr(1);

if (visited.has(path.node) || sourcePath.indexOf('!') !== -1) {
return;
}

if (loaderMap[ext]) {
path.replaceWithMultiple(
path.node.specifiers.map(specifier => {
if (t.isExportDefaultSpecifier(specifier)) {
const newDefaultImport = t.exportDeclaration(
[
t.exportDefaultSpecifier(
t.identifier(specifier.local.name)
),
],
t.stringLiteral(sourcePath)
);

visited.add(newDefaultImport);
return newDefaultImport;
}

const newImport = t.exportNamedDeclaration(
null,
[
t.exportSpecifier(
t.identifier(specifier.local.name),
t.identifier(specifier.exported.name)
),
],
t.stringLiteral(
loaderMap[ext][specifier.local.name]
? loaderMap[ext][specifier.local.name].replace(
/\[path\]/,
sourcePath
)
: sourcePath
)
);

visited.add(newImport);
return newImport;
})
);
}
},
ImportDeclaration(
path,
{
Expand Down