Imagine you're reading the documentation for a new library and come across the perfect code snippet for your project. You copy it, but where should you store it? A random file? VS Code snippets? A GitHub gist? Months later, when you need it again, you can't recall where you saved it or the context in which you found it.
We’ve all faced this challenge. While copying code snippets is straightforward, preserving their context—like the source URL, version information, and why they were useful—is often neglected because it's tedious to document manually.
In this tutorial I will show you how you can avoid this clutter and integrate all your snippets into a single place by using Obsidian and Readwise. By highlighting a code snippet while reading, you can automatically save both the code and its complete context. In this guide, we'll show you how to build a code snippet library that remains useful over time, and even how to integrate it with Visual Studio Code for seamless coding.
1. Introducing Obsidian and Readwise
Obsidian
Obsidian is a powerful knowledge base that works on top of a local folder of plain text Markdown files. It's designed for note-taking and creating a personal knowledge management system. Key features include:
- Creating and linking notes
- Support for plugins and customizations
- Local-first approach, ensuring your data remains in your control
For example, you might create a note about React hooks that links to your existing notes on JavaScript and state management, building a web of interconnected knowledge.
Readwise
Readwise helps you get the most out of what you read by allowing you to:
- Import highlights from various sources (Kindle, Instapaper, articles, etc.)
- Review and remember what you've read through spaced repetition
- Sync your highlights and notes to other apps
For instance, when reading Clean Code by Robert C. Martin on your Kindle, you can highlight code examples and have them automatically synced to your knowledge base.
2. Setting Up Your Environment
a. Install Obsidian
- Download and install Obsidian from obsidian.md.
-
Create a new vault called
DevSnippets
. - Create initial folders for organization:
DevSnippets/
├── Languages/
│ ├── JavaScript/
│ ├── Python/
│ └── SQL/
├── Frameworks/
│ ├── React/
│ └── Node/
└── Templates/
b. Setting up Readwise
- Go to readwise.io and create an account if you don't already have one.
- Install the Readwise browser extension compatible with your browser.
- Test the extension by highlighting any code snippet from a website or documentation.
c. Install the Readwise Official Plugin in Obsidian
- In Obsidian, go to Settings > Community plugins.
- Browse and install the Readwise Official plugin.
- Configure it with your API key (found at readwise.io/access_token).
3. Capturing Code Snippets with Readwise
Let's walk through capturing and organizing a React hook:
Example: Capturing a Custom Hook
While reading an article about React hooks, you find this useful custom hook:
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
});
const setValue = value => {
setStoredValue(value);
window.localStorage.setItem(key, JSON.stringify(value));
};
return [storedValue, setValue];
}
- Highlight the code using the Readwise browser extension.
-
Add tags:
#react
,#hooks
,#localStorage
. - Add a note: "Useful custom hook for persistent state management."
4. Organizing Code Snippets in Obsidian
a. Create a Code Snippet Template
In the Templates
folder, create a new note called Code Snippet Template
:
---
Title: {{title}}
Language: {{language}}
Tags: {{tags}}
Source: {{source}}
Date Captured: {{date}}
---
## Description
{{description}}
## Code
{{language}}
{{code}}
## Usage Example
{{language}}
{{usage}}
## Notes
{{notes}}
## Related Snippets
{{related}}
b. Configure Readwise Plugin
Set up custom formatting in the plugin settings to match your template:
Format:
Title: "{{title}}"
Highlight: "{{highlight}}"
Tags: "{{tags}}"
Source: "{{source}}"
Date: "{{date}}"
URL: "{{url}}"
c. Example of an Imported Snippet
Here's how the useLocalStorage
hook would appear in Obsidian after import:
---
Title: useLocalStorage React Hook
Language: JavaScript
Tags: #react #hooks #localStorage
Source: "Advanced React Patterns" by Kent C. Dodds
Date Captured: 2023-10-15
---
## Description
A custom React hook that synchronizes state with localStorage for persistent data storage across page reloads.
## Code
javascript
function useLocalStorage(key, initialValue) {
// ... code ...
}
## Usage Example
javascript
function App() {
const [name, setName] = useLocalStorage("userName", "");
return (
type="text"
value={name}
onChange={e => setName(e.target.value)}
/>
);
}
## Notes
- Handle `JSON.parse` errors for corrupted localStorage data.
- Consider adding compression for larger data structures.
- Test in incognito mode for localStorage availability.
## Related Snippets
- [[Custom React Hooks Collection]]
- [[Browser Storage Options]]
- [[State Management Patterns]]
5. Enhancing Your Code Snippet Library
a. Organize Tags
Create a structured tag hierarchy to keep your snippets organized:
#javascript
#javascript/react
#javascript/react/hooks
#javascript/react/components
#javascript/react/state
#javascript/node
#javascript/node/express
#javascript/node/middleware
b. Link Related Concepts
Establish connections between related snippets and concepts:
In your `useLocalStorage` hook note:
This hook implements the [[Observer Pattern]] for watching localStorage changes and utilizes [[React's useState Hook]] internally.
See also: [[Custom Hook Best Practices]]
6. Maintaining Original References
Create a source note for "Advanced React Patterns":
---
Title: Advanced React Patterns
Author: Kent C. Dodds
Type: Course
Platform: Frontend Masters
Date: 2023
---
## Key Concepts Covered
- Custom Hooks
- Compound Components
- State Reducers
## Code Snippets
- [[useLocalStorage React Hook]]
- [[useMediaQuery Hook]]
- [[useReducer Example]]
## Review Status
Last reviewed: 2023-10-15
Next review: 2023-11-15
7. Using Your Snippets in Visual Studio Code
To further enhance your workflow, you can access and use your Obsidian code snippets directly within Visual Studio Code (VS Code). This integration allows you to seamlessly reference your personal snippet library while coding.
a. Install the Obsidian MD for VSCode Extension
To connect Obsidian with VS Code, you'll use the Obsidian MD for VSCode extension. This extension enables you to interact with your Obsidian notes directly from within VS Code.
- Install the Extension:
- Open VS Code.
- Go to the Extensions view by clicking on the Extensions icon in the Activity Bar or pressing
Ctrl+Shift+X
(Cmd+Shift+X
on Mac). - Search for "Obsidian MD for VSCode".
- Click Install to add the extension to VS Code.
b. Configure the Extension
- Install Required Plugins in Obsidian:
- In Obsidian, go to Settings > Community plugins.
- Install the Advanced URI plugin. This plugin allows external applications like VS Code to interact with Obsidian notes via URIs.
- Set Up Default Vault and Note in VS Code:
- Open the Command Palette in VS Code (
Ctrl+Shift+P
orCmd+Shift+P
on Mac). - Run the command
Obsidian MD: Set Default Vault and Note (Global)
to set your default Obsidian vault and default note.
- Adjust Extension Settings (Optional):
- Go to File > Preferences > Settings (
Ctrl+,
orCmd+,
on Mac). - Search for "Obsidian MD for VSCode" to adjust settings such as the default vault path or button classes.
c. Accessing and Using Snippets
- Open Your Obsidian Vault in VS Code:
- Use the command
Obsidian MD: Open vault in VSCode
to open your entire Obsidian vault in the VS Code file explorer. - Navigate your notes and snippets just like any other files.
- Insert Backlinks and Notes from VS Code:
- With the extension, you can send information directly to your Obsidian notes from VS Code.
- Highlight code or text in VS Code, then use the command
Obsidian MD: Connect with Obsidian
to open a menu of actions. - Choose to append or prepend the selected text to your default note or daily note in Obsidian.
- Create backlinks from your code files to Obsidian notes, making it easy to navigate between your code and the relevant documentation.
- Use Backlinks in Your Code:
- The extension allows you to insert backlinks into your code files, which link back to specific notes in Obsidian.
- For example, you can add a comment in your code that links to the Obsidian note where the code snippet is documented.
- Leverage VS Code Features:
- Utilize VS Code's advanced search and navigation capabilities to find code snippets and notes quickly.
- Open markdown files directly in VS Code to view and edit your snippets without switching between applications.
d. Keep Snippets Updated
- Any changes you make to your snippets in Obsidian will reflect in VS Code if you refresh or reopen the files.
- Use Git or another version control system to track changes to your snippet library.
Conclusion
By integrating Obsidian, Readwise, and Visual Studio Code, you've created a powerful system for managing code snippets that retains valuable context and is readily accessible within your coding environment. This approach not only saves time but also enhances your productivity by keeping essential information at your fingertips.
Customize these templates and workflows to match your specific needs and preferences. The flexibility of these tools allows you to adapt the system as your requirements evolve.
With this integrated approach, you not only save code snippets but also preserve the rich context that makes them truly valuable, ensuring you can find and effectively use them whenever needed.
Top comments (0)