Skip to content

Named exports as default export #26

Description

@niksy

native-url exposes methods thorugh named exports. To get default Node url behavior you would need to import entire module contents

import * as url from 'native-url'; // or 'url' if aliased`

This is fine for your own code, but dependencies will throw error since they can’t find default export by default, and most 3rd party code using Node url depend on that default export to be available.

To fix this, it’s best to make changes to code at compile time to expose every named export as property of object which should be default export.

Here is a Babel plugin code which achieves that:

const babel = require('@babel/core');

const plugin = babel.createConfigItem(({ types: t }) => {
	return {
		visitor: {
			ExportNamedDeclaration(path, parent) {
				const properties = path.node.specifiers.map((node) => ({
					exported: node.exported.name,
					local: node.local.name
				}));
				path.insertAfter(
					t.exportDefaultDeclaration(
						t.objectExpression(
							properties.map((prop) =>
								t.objectProperty(
									t.identifier(prop.exported),
									t.identifier(prop.local)
								)
							)
						)
					)
				);
			}
		}
	};
});

And here is how you apply it with Webpack:

{
	test: /\.m?js$/,
	include: /node_modules\/native-url/,
	use: [
		{
			loader: 'babel-loader',
			options: {
				plugins: [plugin]
			}
		}
	]
};

After that you can use both modules’ named exports as default export.

Is this something which should be documented for both Webpack and Rollup, or should native-url expose default export by default?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions