Supabase开源项目解析:Apple Silicon M1环境配置与开发实践

云信安装大师
90
AI 质量分
4 5 月, 2025
5 分钟阅读
0 阅读

Supabase开源项目解析:Apple Silicon M1环境配置与开发实践

引言

Supabase是一个开源的Firebase替代品,提供了PostgreSQL数据库、身份验证、即时API等功能。对于使用Apple Silicon M1芯片的开发者来说,配置Supabase开发环境可能会遇到一些特有的问题。本文将详细介绍如何在M1 Mac上搭建Supabase开发环境,并分享一些实践技巧。

准备工作

在开始之前,请确保你的设备满足以下要求:
– Apple Silicon M1/M2芯片的Mac电脑
– macOS Monterey或更高版本
– 已安装Homebrew(如果没有安装,可运行/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
– Node.js (建议使用16.x或更高版本)
– Docker Desktop (支持Apple Silicon版本)

步骤一:安装依赖项

首先我们需要安装Supabase CLI工具和其他必要的依赖:

代码片段
# 安装Supabase CLI
brew install supabase/tap/supabase

# 安装Node.js (通过nvm管理版本)
brew install nvm
mkdir ~/.nvm
echo 'export NVM_DIR="$HOME/.nvm"' >> ~/.zshrc
echo '[ -s "/opt/homebrew/opt/nvm/nvm.sh" ] && \. "/opt/homebrew/opt/nvm/nvm.sh"' >> ~/.zshrc
source ~/.zshrc
nvm install 16

# 安装Docker Desktop for Apple Silicon
# 从官网下载: https://www.docker.com/products/docker-desktop/

注意事项
1. M1芯片需要使用ARM64架构的Docker镜像
2. 确保Docker Desktop的资源分配足够(建议至少4GB内存)

步骤二:初始化Supabase项目

创建一个新的项目目录并初始化Supabase:

代码片段
mkdir my-supabase-project && cd my-supabase-project

# 初始化Supabase配置
supabase init

# 启动本地开发环境(这会启动Docker容器)
supabase start

执行supabase start后,你会看到类似下面的输出:

代码片段
Started supabase local development setup.

         API URL: http://localhost:54321
     GraphQL URL: http://localhost:54321/graphql/v1
          DB URL: postgresql://postgres:postgres@localhost:54322/postgres
      Studio URL: http://localhost:54323
    Inbucket URL: http://localhost:54324
      JWT secret: super-secret-jwt-token-with-at-least-32-characters-long
Anon key: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Service role key: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

原理说明
supabase init会创建默认配置文件supabase/config.toml
supabase start会启动多个Docker容器,包括PostgreSQL数据库、GoTrue(认证)、Storage等组件

步骤三:连接数据库

你可以使用psql命令行工具或者图形化工具连接本地数据库:

代码片段
psql -h localhost -p 54322 -U postgres -d postgres

# 密码是"postgres"

或者使用TablePlus等图形化工具:
– Host: localhost
– Port: 54322
– User: postgres
– Password: postgres
– Database: postgres

步骤四:创建前端应用并连接Supabase

让我们创建一个简单的React应用来连接Supabase:

代码片段
npx create-react-app supabase-demo --template typescript
cd supabase-demo
npm install @supabase/supabase-js @types/node --save-dev

修改src/App.tsx文件:

代码片段
import { useState, useEffect } from 'react';
import { createClient } from '@supabase/supabase-js';

// 使用之前supabase start输出的信息替换下面这些值
const supabaseUrl = 'http://localhost:54321';
const supabaseKey = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'; // anon key

const supabase = createClient(supabaseUrl, supbaseKey);

function App() {
  const [todos, setTodos] = useState<any[]>([]);

  useEffect(() => {
    fetchTodos();
  }, []);

  const fetchTodos = async () => {
    const { data, error } = await supbase.from('todos').select('*');
    if (data) setTodos(data);
    if (error) console.error('Error:', error);
  };

  return (
    <div>
      <h1>My Todos</h1>
      <ul>
        {todos.map((todo) => (
          <li key={todo.id}>{todo.task}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

注意事项
1. M1芯片可能需要额外配置Node.js的原生模块编译环境:

代码片段
npm config set python python3 # Node-gyp需要Python3
npm config set node_gyp $(which node-gyp)<br>
   

  1. TypeScript用户应确保安装了正确的类型定义:
    代码片段
    npm install --save-dev @types/react @types/react-dom @types/node @supbase/supbase-js/typescript-helpers <br>
    

步骤五:创建数据库表并测试API

让我们通过SQL创建一个简单的表并测试API:

代码片段
-- SQL命令可以在psql中执行或通过Studio UI执行(http://localhost:54323)
CREATE TABLE todos (
    id SERIAL PRIMARY KEY,
    task TEXT NOT NULL,
    is_complete BOOLEAN DEFAULT false,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT now()
);

INSERT INTO todos (task) VALUES ('Learn Supbase'), ('Build an app');

然后在前端应用中你应该能看到这些待办事项。

M1特有问题的解决方案

Docker镜像兼容性问题

某些服务可能需要特定的ARM64镜像。如果遇到问题,可以尝试:

代码片段
# 查看当前运行的容器状态确保所有服务都正常启动:
docker ps 

# 如果某个服务失败,可以尝试手动拉取ARM64镜像:
docker pull --platform linux/arm64 postgres:13-alpine 

Node.js原生模块编译问题

某些npm包可能需要重新编译才能兼容M1芯片:

代码片段
rm -rf node_modules package-lock.json # macOS下可能需要 sudo chown -R $(whoami) node_modules/
npm rebuild # 强制重新编译所有原生模块 

Postgres性能优化

M1芯片上的PostgreSQL性能可以通过调整Docker资源限制来优化:
1. Docker Desktop → Preferences → Resources → Memory → ≥4GB RAM
2. CPU核心数建议设置为4或更多

Supbase Studio的使用

访问 http://localhost:54323打开本地Supbase Studio:

在这里你可以:
– GUI方式管理数据库表
– SQL编辑器直接执行查询
– API文档查看自动生成的API端点
– Auth管理用户认证

API测试示例代码

让我们测试一下自动生成的REST API:

代码片段
// REST API示例代码 (可以直接在浏览器控制台测试)
fetch('http://localhost:54321/rest/v1/todos', {
    headers: {
        'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...', // anon key,
        'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...' // same as apikey for anon access  
    }
})
.then(res => res.json())
.then(console.log);

你应该能看到之前插入的两条待办事项。

Authentication设置示例

让我们启用电子邮件登录功能:

代码片段
// auth示例代码 (添加到你的React应用中)
const handleSignUp = async () => {
    const { user, error } = await supase.auth.signUp({
        email: 'user@example.com',
        password: 'password'
    });

    if (error) alert(error.message);
    else alert('Check your email for the confirmation link!');
};

const handleLogin = async () => {
    const { user, error } = await supase.auth.signIn({
        email: 'user@example.com',
        password: 'password'
    });

    if (error) alert(error.message);
};

在Studio的Authentication → Settings中启用电子邮件登录。

Storage功能示例代码

让我们测试一下文件存储功能:

代码片段
// storage示例代码 
const uploadFile = async () => {
    const fileInput = document.getElementById('file-input');

    if (!fileInput.files.length) return;

    const file = fileInput.files[0];

    // bucket名称需要先在Studio中创建(Storage → New bucket)
    const { data, error } = await supase.storage.from('avatars').upload(`public/${file.name}`, file);

    if (error) console.error(error);
};

// Get download URL for a file:
const getFileUrl = async () => {
    const { publicURL, error } = await supase.storage.from('avatars').getPublicUrl(`public/${filename}`);
};

Realtime功能示例代码

让我们启用实时更新功能:

代码片段
// realtime订阅示例代码 
useEffect(() => {
    const subscription = supase.from('todos')
        .on('*', payload => {
            console.log('Change received!', payload); 
            fetchTodos(); // refresh our todo list when changes occur  
        })
        .subscribe();

    return () => {
        subscription.unsubscribe();
};}, []);

在Studio的Database → Replication中启用表的实时功能。

Edge Functions配置(可选)

如果你需要使用Edge Functions:

代码片段
# Edge Functions需要Deno运行时(已包含在最新CLI中)
supase functions new hello-world 

# Edit the function in ./supase/functions/hello-world/index.ts 

# Deploy the function locally:
supase functions deploy hello-world 

# Then you can call it from your frontend:
await supase.functions.invoke('hello-world', { body: JSON.stringify({ name }) });

Production部署准备

当你准备好部署到生产环境时:

代码片段
# Link your project to a Supase project in the cloud:
supase login # follow the prompts to authenticate  

# Create a new project in the cloud:
supase projects create my-project --org-id=your_org_id 

# Push your local schema to production:
supase db push --db-url=your_production_db_url 

# Deploy edge functions to production:
supase functions deploy hello-world --project-ref=your_project_ref  

Troubleshooting常见问题解决

Docker容器无法启动

如果supase start失败:

代码片段
docker system prune # clean up old containers/images  

sudo rm -rf ~/.local/share/supase # reset local dev setup  

then run `supase start` again  

Postgres连接问题

检查端口是否正确(Mac上默认为54322而不是标准的5432):

代码片段
psql -h localhost -p 54322 -U postgres  
password is "postrese"  

Node.js包安装失败

对于原生模块编译问题:

代码片段
export npm_config_arch=arm64 # force ARM64 builds  

npm rebuild # recompile all native modules  

Edge Functions无法工作

确保Deno运行时正确安装:

代码片段
deno --version # should be v1.20+  

if not installed, run `brew install deno`  

Conclusion总结

在Apple Silicon M1上配置Supbase开发环境需要注意以下几点关键事项:

  1. 架构兼容性: Docker镜像和Node.js原生模块需要ARM64版本
  2. 资源分配: Docker Desktop需要足够的内存和CPU资源
  3. CLI工具: Supbase CLI已经针对M1优化,保持最新版本即可
  4. 性能优势: M1芯片能提供更快的本地开发体验

通过本文的详细步骤,你应该已经成功搭建了完整的本地开发环境。接下来可以探索更多Supbase的高级功能如Row Level Security、PostgreSQL函数等。Happy coding!

原创 高质量