Search code examples
typescriptecmascript-6es6-modules

Is it possible to import from an existing import?


Here are some examples that help explain my question:

// ex 1, works
import { MessageAttributeMap } from "aws-sdk/clients/sns";

// ex 2, works
import * as AWS from "aws-sdk";
type MessageAttributeMap = AWS.SNS.MessageAttributeMap

// ex 3, does not work
import * as AWS from "aws-sdk";
import { MessageAttributeMap } from AWS;

Example 3 does not work but I was curious if there is a way to perform an import from an existing import?

Is there an alternative way of making ex 2 work with MessageAttributeMap without using AWS.SNS.MessageAttributeMap?

UPDATE - adding context to the problem

I have several projects (project a, b, c) that use aws-sdk with the same version. In an attempt reduce the amount of package updates and have all projects use the same version of aws-sdk, I've created a common project (common) that contains aws-sdk. I've updated all 3 projects to include this common project as a dependency and removed aws-sdk from the 3 projects.

Exporting aws-sdk in common project index.ts:

export * as AWS from "aws-sdk";

Add common as a dependency in each project's package.json:

"@test/common": "file:../../libs/common"

Now that I've imported the common project, I would like to update the existing imports to use aws-sdk in the common project from this

import * as AWS from "aws-sdk";
import { MessageAttributeMap } from "aws-sdk/clients/sns";

to this, if possible

import { AWS as aws } from "@test/common"; // works
import { MessageAttributeMap } from aws; // does not work

Solution

  • The simple answer to your question is no, since when you call import * as AWS you have at that point already imported the entire package into an object. At this point you interact with AWS as a regular object, so something like:

    const { SNS: { MessageAttributeMap } } = AWS;
    

    However, if you have a common package, then that makes things a bit easier. What I suggest you do, is import AWS in your common package, then only export those parts you want. So For instance:

    // packages/common/src/index.ts
    import * as AWS from 'aws-sdk';
    
    const { SNS: { MessageAttributeMap } } = AWS;
    
    export MessageAttributeMap;
    

    In this way you only export those things you want, directly from your custom workspace, allowing you to import as:

    import { MessageAttributeMap } from 'aws';