关于 Astro
Astro是一个适合以内容驱动的网站的web框架。当前的这个知识库,就是用Astro搭建的,属于其中的全静态网站,即每次编辑完markdown文档之后,直接同步到github,接着cloudflare worker就会自动拉取最新版本并部署,生成静态文件,加速访问
Astro的官方网址为: https://astro.build
常用功能的安装
安装Astro
在终端中,运行 npm create astro@latest 来创建一个新项目,按照提示进行即可。
添加集成
Astro官方提供了一些常用的集成,比如cloudflare 适配器,tailwind等,能够无缝跟Astro进行集成。
添加的命令如:
npx astro add cloudflare 添加cloudflare 适配器
npx astro add tailwind 添加tailwindcss作为css
官方集成在添加库的同时,还会在相应的配置文件中增加对应的代码,属于傻瓜型,能用官方库的尽量用官方集成
目前用过的集成
npx astro add cloudflare用于将web部署到cloudflare worker上npx astro add tailwind用于将tailwind添加到astro中npx astro add node用于将web部署到本地或者其他服务器npx astro add solid使用solidjs组件实现渲染和客户端水和npx astro add react使用react组件实现渲染和客户端水和
Astro 文件夹说明
Astro 部署
通用性设置
// astro.config.mjs 文件
export default defineConfig({
output: 'server' // server --> ssr 网站 | static --> 静态网站
adapter:node({
mode:'standalone', // 生成独立服务器,不依赖外部 HTTP 服务器
}),
server:{
port:3000, // 这里配置端口
stricPort:false, // 默认就是 false,端口被占时自动递增
host:true, //
}
})
cloudflare 环境部署
cloudflare 环境部署
使用 npx astro add cloudflare,然后按照提示一步一步进行。
环境变量
当要使用环境变量时,需要从cloudflare:workers中导入
---
import { env } from 'cloudflare:workers';
const myVariable = env.MY_VARIABLE;
const myKVNamespace = env.MY_KV;
---
需要使用cloudflare的cf对象时,则需要如下:
---
const cf = Astro.request.cf;
const country = cf?.country;
---
需要在waitUntil() 中的操作,需要从Astro.locals.cfContext 中读取
---
const cfContext = Astro.locals.cfContext;
cfContext.exports.Greeter.greet('Astro');
cfContext.waitUntil(someAsyncOperation());
---
假如需要用到node中的内容时,要配置好下面的内容:
{
"compatibility_flags": ["nodejs_compat"],
}
node 环境部署
安装node环境
使用 npx astro add node 来配置好node的环境,然后修改 astro.config.mjs文件。
node 环境配置
import { defineConfig } from 'astro/config';
import node from '@astrojs/node';
import react from '@astrojs/react';
import tailwindcss from '@tailwindcss/vite';
import path from 'path';
export default defineConfig({
output: 'server',
adapter: node({
mode: 'standalone',
experimentalDisableStreaming: true // 开启html流式传输
}),
server: {
port: 7878,
host: true,
},
security: {
checkOrigin: true,
allowedDomains: [
{
hostname: 'door.weadb.com', //这里配置好,可以使用cloudflare tunnels反代
protocol: 'https',
},
{
hostname: '*.weadb.com',
protocol: 'https',
},
],
},
vite: {
plugins: [tailwindcss()],
optimizeDeps: {
exclude: ['better-sqlite3']
},
resolve: {
alias: {
'@': path.resolve('./src')
}
},
}
});
中间件
服务器入口文件默认构建为 ./dist/server/entry.mjs,所以在supervisor的配置文件里,可以使用 node ./dist/server/entry.mjs
配置Nginx
server {
listen 80;
server_name your-domain.com;
client_max_body_size 50M; # 允许上传大文件
location / {
proxy_pass http://127.0.0.1:4321;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_read_timeout 86400;
}
}