SingleImportStatement

Represents a static import statement in an ES module. SingleImportStatemnts are used inside TargetableESModule methods to keep track of the new dependencies being added to the module, and to resolve conflicts when they occur.

The typical way to add new imports to a TargetableESModule is to pass a static import statement. The import statement can accomplish two things:

  • It’s already a familiar syntax
  • It contains the module path, the exports of the module to import, and the local binding names for those imports

That’s almost all we need to do the import management we need, including deduping and scope conflict resolution.

Parameters

Name Type Description
statement string A static import statement

Creates a new SingleImportStatement object with a different binding.

**Returns: ** SingleImportStatement — A new SingleImportStatement that is a copy of this one, but with the binding renamed. The originalStatement and statement properties are rewritten to use the new binding.

Parameters

Name Type Description
newBinding string Binding to rename.

When interpolated as a string, a SingleImportStatement becomes the value of its binding property.

**Returns: ** string

Source Code: pwa-studio/packages/pwa-buildpack/lib/WebpackTools/targetables/SingleImportStatement.js

Examples

Code examples for using the SingleImportStatement class.

Create a SingleImportStatement object

Pass in an import statement to the constructor to create a new SingleImportStatement object.

const queryHookImport = new SingleImportStatement("import { useQuery } from '@apollo/react-hooks'");

This creates an object with the following properties:

{
  statement: "import { useQuery } from '@apollo/react-hooks'",
  binding: 'useQuery',
  imported: 'useQuery'
}

Change the binding

Use the changeBinding() function to rename the variable bound to the imported object.

const queryHookImport = new SingleImportStatement("import { useQuery } from '@apollo/react-hooks'");

const queryHookImport2 = useQueryImport.changeBinding('useQuery2');

This creates an object with the following properties:

{
  statement: "import { useQuery as useQuery2 } from '@apollo/react-hooks'",
  binding: 'useQuery2',
  imported: 'useQuery'
}

Using the SingleImportStatement object

The toString() value of a SingleImportStatement object is the value of the binding property. Use this to reference the component’s local name when adding custom code with Targetables.

// You can skip 'import' and the class is able to understand what you mean
let Button = new SingleImportStatement("Button from './button'");

// later, you learn there is a conflict with the `Button` identifier,
// so you generate a unique identifier
Button = Button.changeBinding(generateUniqueIdentifier());

// this renders the new identifier for your Button import in the final code
const jsx = `<${Button}>hello world</${Button}>`