In this lesson, you will:
Solidity uses the import directive to include code from other files, similar to JavaScript imports. This feature allows you to incorporate constants, structs, enums, events, functions, and contracts from external files. Unlike JavaScript, Solidity doesn’t have an export statement or default export.
Import Directive:
In Solidity, the import directive is used to integrate other Solidity files into your contract. For instance, importing the Solana library lets you utilize its methods within your Solidity contracts. Solidity's approach to imports is somewhat akin to JavaScript's ES6, with some differences.
Example:
import { foo, bar } from "defines.sol";
In Solidity, import
is hoisted, allowing foo
and bar
to be accessible before the import statement.
Types of Imports:
There are several types of imports you can use:
import "defines.sol";
This imports all items from "defines.sol", differing from ES6 where such syntax imports nothing.
import { foo, bar } from "defines.sol";
Only imports foo
and bar
from "defines.sol".
import map @openzeppelin=/opt/openzeppelin-contracts/contracts
import "@openzeppelin/interfaces/IERC20.sol";
This would link to /opt/openzeppelin-contracts/contracts/interfaces/IERC20.sol
.
You can also rename imports for convenience or to avoid name clashes:
import { bar as baz, foo } from "defines.sol";
This renames bar
to baz
from "defines.sol".
Grouping Imports Under a Namespace:
import "defines.sol" as defs;
// Now use defs.bar, defs.foo, etc.
This groups all imports from "defines.sol" under the defs
namespace.
Next, we'll delve into pragma directives in Solidity,
an essential aspect of setting up your Solidity environment for Solana programming. Pragma directives dictate compiler behaviour and compatibility, ensuring your code is interpreted correctly.