Skip to main content

Installation

Installing Obsidian is a straightforward process that involves adding the package to your project, enabling TypeScript decorators, and adding Obsidian's transformer to your build system, either Babel or SWC. Let's go through the steps.

1. Install Obsidian

Install the package using your preferred package manager:

yarn add react-obsidian

2. Install Reflect-metadata

First, install the reflect-metadata package:

yarn add reflect-metadata

Then, enable the reflect-metadata polyfill by adding the following line to the top of your application's entry point (usually index.js or index.ts):

import 'reflect-metadata';

3. Enable experimental decorators

Obsidian uses the Decorators feature whose proposal is at stage 3.

Add the following options to your tsconfig.json file.

{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}

4. Add Obsidian's transformer

Like most Dependency Injection frameworks, Obsidian uses automatic code generation to create the bindings necessary for resolving dependencies. This approach helps reduce the amount of boilerplate code required by developers.

You'll need to add either the Babel or SWC plugins depending on your project's configuration.

  • React Native: React Native projects only support Babel, so you'll need to use the Babel plugin.
  • Vite: Vite supports both Babel and SWC. Choose the one according to your project's build system.
  • NextJS: NextJS supports both Babel and SWC. If your project uses the next/font package you'll have to use the SWC plugin as next/font doesn't support Babel.

Install the required Babel plugins

You will need to install these plugins if you don't have them already:

yarn add @babel/plugin-proposal-decorators @babel/plugin-transform-class-properties babel-plugin-parameter-decorator @babel/core @babel/preset-env @babel/preset-typescript

If this is your first time using Babel, you will also need to install Babel's core packages:

yarn add @babel/core @babel/preset-env @babel/preset-typescript

Update your Babel configuration

Add the transformer and the required plugins to the list of plugins in your babel.config.js file or .babelrc file:

module.exports = {
presets: [
'module:metro-react-native-babel-preset',
+ ['@babel/preset-typescript', {'onlyRemoveTypeImports': true}]
],
plugins: [
+ react-obsidian/dist/transformers/babel-plugin-obsidian,
+ ['@babel/plugin-proposal-decorators', {legacy: true}],
+ '@babel/plugin-transform-class-properties',
+ 'babel-plugin-parameter-decorator'
]
};

5. Optional - Add Obsidian's ESLint plugin

Obsidian provides an ESLint plugin that can help you find errors in your code related to dependency injection. See the ESLint plugin documentation for more information.