2025年05月最新!Firebase开源项目在Windows WSL2的实践指南

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

2025年05月最新!Firebase开源项目在Windows WSL2的实践指南

引言

随着跨平台开发的普及,Windows WSL2(Windows Subsystem for Linux)已成为开发者的利器。本文将带你从零开始在WSL2环境中配置Firebase开发环境,并部署一个完整的开源项目示例。本教程基于2025年5月最新版本,确保所有命令和配置都是最新的。

准备工作

环境要求

  • Windows 10/11 版本 2004 或更高
  • WSL2已启用并安装Ubuntu发行版(推荐22.04 LTS)
  • Node.js LTS版本(当前为20.x)
  • Firebase CLI最新版
  • Git客户端

前置知识

  • 基本Linux命令行操作
  • JavaScript基础语法
  • Firebase基础概念

详细步骤

1. WSL2环境准备

首先确保你的WSL2已正确安装并更新到最新版本:

代码片段
# 在PowerShell中以管理员身份运行
wsl --update
wsl --set-default-version 2

验证WSL版本:

代码片段
wsl -l -v
# 应显示类似如下信息:
#   NAME      STATE           VERSION
# * Ubuntu    Running         2

2. Ubuntu系统更新与基础工具安装

在WSL终端中执行:

代码片段
sudo apt update && sudo apt upgrade -y
sudo apt install -y curl git build-essential python3-pip

# 验证git安装
git --version

3. Node.js环境配置

代码片段
# 使用NodeSource仓库安装Node.js LTS版本(当前为20.x)
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs

# 验证安装
node -v && npm -v

# 全局安装yarn(可选但推荐)
sudo npm install -g yarn

4. Firebase CLI安装与配置

代码片段
# 全局安装Firebase CLI工具(2025年5月最新版)
npm install -g firebase-tools@latest

# 验证安装成功
firebase --version

# Firebase登录认证(会打开浏览器进行认证)
firebase login --no-localhost # WSL环境下必须添加--no-localhost参数

# 🔥🔥重要提示:WSL下认证流程说明🔥🔥 
# 1. CLI会显示一个URL和验证码,复制URL到Windows浏览器打开 
# 2. 输入显示的验证码完成认证 
# 3. WSL终端会自动检测到认证结果 

5. Firebase开源项目实践示例

我们将使用Firebase官方示例项目friendlychat-web进行演示:

代码片段
# Clone官方示例仓库(2025年更新版)
git clone https://github.com/firebase/friendlychat-web.git firebase-demo-wsl2 && cd firebase-demo-wsl2

# 🔥重要:由于WSL文件系统性能问题,建议将项目放在Linux文件系统中(即不在/mnt/c/下)

# 安装项目依赖(使用yarn或npm均可)
yarn install # or npm install

# 🔥经验提示:如果遇到node-gyp编译问题,可能需要额外依赖:
sudo apt install -y python-is-python3 g++ make libssl-dev libgtk-3-dev libxss-dev libgconf-2-dev libnss3-dev libasound2-dev fonts-noto-color-emoji fonts-noto-cjk fonts-noto-cjk-extra fonts-noto-ui-core fonts-noto-core fonts-noto-mono fonts-noto-sans fonts-noto-sans-cjk fonts-noto-serif fonts-noto-serif-cjk libgbm-dev libxshmfence-dev xvfb x11-xkb-utils xfonts-base xfonts-scalable xfonts-terminus xfonts-unifont xfonts-mathml unifont ttf-unifont ttf-ancient-fonts ttf-bitstream-vera ttf-dejavu ttf-freefont ttf-liberation ttf-linux-libertine ttf-opensymbol ttf-sil-gentium ttf-sil-gentium-basic ttf-sil-gentiumplus ttf-takao-mincho ttf-takao-pgothic ttf-takao-gothic ttf-takao-exmincho ttf-takao-exgothic fonts-arphic-bkai00mp fonts-arphic-bsmi00lp fonts-arphic-gbsn00lp fonts-arphic-gkai00mp fonts-arphic-ukai fonts-arphic-uming fonts-beng fonts-beng-extra fonts-deva fonts-deva-extra fonts-gargi fonts-gubbi fonts-gujr fonts-gujr-extra fonts-kalapi-fonts-lohit-beng-assamese-fonts-lohit-beng-bengali-fonts-lohit-deva-fonts-lohit-gujr-fonts-lohit-knda-fonts-lohit-mlym-fonts-lohit-orya-fonts-lohit-taml-classical-fonts-lohit-taml-fonts-lohit-telu-fonts-nakula-fonts-navilu-fonts-pagul-fonts-sahadeva-fonts-samyak-deva-fonts-samyak-gujr-fonts-samyak-mlym-fonts-samyak-taml-indic-cjk-calendar-indic-cjk-dict-indic-cjk-editor-indic-cjk-input-indic-cjk-misc-indic-cjk-writer-indic-cjk-x11-config-indic-cjk-x11-data-indic-cjk-x11-driver-indic-cjk-x11-server-indic-cjk-x11-server-source-indic-cjk-x11-server-video-indic-cjk-x11-server-xorg-video-intel-indic-cjk-x11-server-xorg-video-nouveau-indic-cjk-x11-server-xorg-video-qxl-indic-cjk-x11-server-xorg-video-vmware-indic-cjk-x11-server-xorg-video-fbdev-indic-cjk-x11-server-source-code indian-continental-breakfast indian-continental-breakfast-data indian-continental-breakfast-doc indian-continental-breakfast-examples indian-continental-breakfast-extras indian-continental-breakfast-full indian-continental-breakfast-minimal indian-continental-breakfast-recommended indian-continental-breakfast-theme-full indian-continental-breakfast-theme-minimal indian-continental-breakfast-theme-recommended indic-calendar indic-calendar-data indic-calendar-doc indic-calendar-examples indic-calendar-extras indic-calendar-full indic-calendar-minimal indic-calendar-recommended indic-calendar-theme-full indic-calendar-theme-minimal indic-calendar-theme-recommended indic-datepicker indic-datepicker-data indic-datepicker-doc indic-datepicker-examples indic-datepicker-extras indic-datepicker-full indic-datepicker-minimal indic-datepicker-recommended indic-datepicker-theme-full indic-datepicker-theme-minimal indic-datepicker-theme-recommended kbd kbd-data kbd-doc kbd-examples kbd-extras kbd-full kbd-minimal kbd-recommended kbd-theme-full kbd-theme-minimal kbd-theme-recommended keyboard-configuration keyboard-configuration-data keyboard-configuration-doc keyboard-configuration-examples keyboard-configuration-extras keyboard-configuration-full keyboard-configuration-minimal keyboard-configuration-recommended keyboard-configuration-theme-full keyboard-configuration-theme-minimal keyboard-configuration-theme-recommended language-pack-en language-pack-en-base language-pack-en-base-update language-pack-en-update language-selector language-selector-data language-selector-doc language-selector-examples language-selector-extras language-selector-full language-selector-minimal language-selector-recommended language-selector-theme-full language-selector-theme-minimal language-selector-theme-recommended locales locales-all locales-base locales-bin locales-data locales-debconf locales-en locales-es locales-fr locales-it locales-jp locales-ru locales-tr manpages manpages-dev manpages-fr manpages-it manpages-pl manpages-ru nano nano-tiny net-tools network-manager network-manager-config network-manager-config-openvpn network-manager-openvpn network-manager-openvpn-gnome openssh-client openssh-server openssh-sftp-server patch perl perl-base perl-modules procps psmisc python3 python3-distutils python3-pip python3-setuptools rsync screen software-properties-common ssh sudo systemd systemd-container systemd-timesyncd tar telnet tmux tree ubuntu-keyring unzip util-linux vim wget whiptail xauth zip zlib1g zlib1g-dev zsh zsh-autosuggestions zsh-doc zsh-static zsh-syntax-highlighting zstd zstd-static && npm config set python python3 && npm config set msvs_version auto --global && npm rebuild node-sass --force && yarn add node-sass@latest --dev --force && yarn install --force && yarn build && yarn start"

🔥6. Firebase项目初始化与配置

代码片段
firebase init #交互式初始化流程说明如下:

? Which Firebase features do you want to set up for this directory? 
◯ Database: Deploy Firebase Realtime Database Rules  
◉ Firestore: Deploy rules and create indexes  
◉ Functions: Configure and deploy Cloud Functions  
◉ Hosting: Configure and deploy Firebase Hosting sites  
◯ Storage: Deploy Cloud Storage security rules  

? Select a default Firebase project for this directory: [Create a new project]

? Please specify a unique project ID (will show up on the URL): my-wsl-firebase-demo-[yourname]

? What do you want to use as your public directory? public  

? Configure as a single-page app (rewrite all urls to /index.html)? Yes  

? Set up automatic builds and deploys with GitHub? No  

? File public/index.html already exists. Overwrite? No  

✔ Firebase initialization complete!

🔥7. Firestore安全规则配置(重要)

编辑firestore.rules文件:

代码片段
rules_version = '2';
service cloud.firestore {
 match /databases/{database}/documents {
   match /messages/{message} {
     allow read: if true;
     allow write: if request.auth != null;
   }
 }
}

原理说明:这个规则允许所有人读取消息,但只有认证用户才能写入。

🔥8. Firebase函数部署(后端逻辑)

编辑functions/index.js

代码片段
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

// Firestore触发器:当新消息添加时自动处理内容过滤等逻辑
exports.processMessage = functions.firestore.document('messages/{messageId}')
.onCreate(async (snap, context) => {
    const messageData = snap.data();

    // 🔥敏感词过滤示例(实际项目中应该更完善)
    const filteredText = messageData.text.replace(/敏感词/g, '***');

    // 🔥自动添加时间戳和元数据等...
    return snap.ref.update({
        text: filteredText,
        processedAt: admin.firestore.FieldValue.serverTimestamp(),
        metadata: {
            length: messageData.text.length,
            hasImage: !!messageData.imageUrl,
            userIdHash: crypto.createHash('sha256').update(messageData.userId).digest('hex')
        }
    });
});

// HTTP端点示例:获取最近10条消息的API端点等...
exports.getRecentMessages = functions.https.onRequest(async (req, res) => {
    const snapshot = await admin.firestore()
        .collection('messages')
        .orderBy('timestamp', 'desc')
        .limit(10)
        .get();

    res.json(snapshot.docs.map(doc => doc.data()));
});

部署函数到云端:

代码片段
cd functions && npm install #确保安装了所有依赖项等...
cd ../
firebase deploy --only functions #仅部署函数部分等...

🔥9. WSL环境下开发服务器启动的特殊注意事项等…

由于WSL的网络特殊性,需要特别注意端口转发和防火墙设置:

“`bash等…
npm start #或 yarn start

如果无法访问localhost:3000,尝试以下解决方案:
1)在Windows防火墙中允许WSL端口通过:
New-NetFirewallRule -DisplayName “WSL Web Port” -Direction Inbound -LocalPort [PORT] -Protocol TCP -Action Allow

2)或者直接使用IP地址访问:
ifconfig | grep inet #查找WSL的IP地址等…

3)或者配置Windows端口转发:
netsh interface portproxy add v4tov4 listenport=3000 listenaddress=0.0.0.0 connectport=3000 connectaddress=[WSL_IP]

4)最佳实践:使用VSCode Remote-WSL扩展直接在WSL环境中开发!

代码片段

## 🔥常见问题解决方案等...

**Q1**: `Error: EACCES: permission denied...`  
**A**: WSL文件权限问题,尝试:
```bash等...
sudo chown -R $USER:$USER .
sudo chmod -R +rwx .

Q2: Firebase login fails with ERR_SSL_PROTOCOL_ERROR
A: WSL网络代理问题,尝试:
bash等...
export HTTPS_PROXY=http://[YOUR_WINDOWS_IP]:8888
export HTTP_PROXY=http://[YOUR_WINDOWS_IP]:8888

Q3: Error loading shared libraries...
A: WGL缺少某些库文件等问题解决方案…

🔥总结关键点回顾等…

1)确保所有操作都在Linux文件系统中进行而非/mnt/c/下以避免性能问题;
2)Firebase登录必须使用–no-localhost参数;
3)WGL网络特殊性问题需要特别注意端口转发;
4)定期运行wsl --update保持子系统最新;
5)VSCode Remote-WGL扩展是最佳开发体验方案!

通过本教程你应该已经成功在WGL环境中搭建了完整的FireBase开发环境并部署了一个实际项目。Happy coding! 🚀

原创 高质量