Instalação e Setup
Instalação via npm/bun
Section titled “Instalação via npm/bun”Usando Bun (Recomendado)
Section titled “Usando Bun (Recomendado)”bun add @_bashell/slashUsando npm
Section titled “Usando npm”npm install @_bashell/slashUsando pnpm
Section titled “Usando pnpm”pnpm add @_bashell/slashUsando yarn
Section titled “Usando yarn”yarn add @_bashell/slashConfiguração TypeScript
Section titled “Configuração TypeScript”Slash é TypeScript-first e requer TypeScript 5.0+. Configure seu tsconfig.json com as opções recomendadas:
{ "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "lib": ["ES2022", "DOM", "DOM.Iterable"], "strict": true, "esModuleInterop": true, "skipLibCheck": true, "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "jsxImportSource": "@_bashell/slash", "types": ["bun-types"] }}Opções importantes
Section titled “Opções importantes”target: "ES2022": Slash utiliza features modernas do JavaScriptstrict: true: Type safety completojsx: "preserve": Para uso com HTM (não é necessário transpilação JSX)moduleResolution: "bundler": Recomendado para Bun e bundlers modernos
Estrutura de Projeto Básica
Section titled “Estrutura de Projeto Básica”Client-Side Rendering (CSR)
Section titled “Client-Side Rendering (CSR)”Estrutura mínima para uma SPA:
my-slash-app/├── src/│ ├── main.ts # Entry point│ ├── App.ts # Root component│ └── components/│ └── Counter.ts├── index.html├── package.json└── tsconfig.jsonindex.html
Section titled “index.html”<!DOCTYPE html><html lang="pt-BR"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My Slash App</title></head><body> <div id="app"></div> <script type="module" src="/src/main.ts"></script></body></html>src/main.ts
Section titled “src/main.ts”import { html, render } from '@_bashell/slash'import { App } from './App'
const root = document.getElementById('app')if (root) { render(html`<${App} />`, root)}src/App.ts
Section titled “src/App.ts”import { html } from '@_bashell/slash'import { Counter } from './components/Counter'
export const App = () => html` <div> <h1>Welcome to Slash!</h1> <${Counter} /> </div>`src/components/Counter.ts
Section titled “src/components/Counter.ts”import { html, createState } from '@_bashell/slash'
// O state fica fora do componente: se fosse criado dentro, seria recriado a cada renderconst count = createState(0)
export const Counter = () => html` <div> <p>Count: ${count.get()}</p> <button onClick=${() => count.set(count.get() + 1)}> Increment </button> </div>`Server-Side Rendering (SSR)
Section titled “Server-Side Rendering (SSR)”Estrutura para aplicação com SSR:
my-slash-ssr/├── src/│ ├── server.ts # Server entry (Bun/Node)│ ├── client.ts # Client entry (hydration)│ ├── App.ts # Shared root component│ └── components/│ └── Counter.ts├── public/│ └── index.html├── package.json└── tsconfig.jsonsrc/server.ts
Section titled “src/server.ts”import { renderToString, serializeStateForScript } from '@_bashell/slash/ssr'import { App } from './App'
const server = Bun.serve({ port: 3000, async fetch(req) { // renderToString retorna { html, state } const { html, state } = renderToString(App)
return new Response(` <!DOCTYPE html> <html lang="pt-BR"> <head> <meta charset="UTF-8"> <title>My SSR App</title> </head> <body> <div id="app">${html}</div> <script id="__SLASH_STATE__" type="application/json">${serializeStateForScript(state)}</script> <script type="module" src="/client.js"></script> </body> </html> `, { headers: { 'Content-Type': 'text/html; charset=utf-8' } }) }})
console.log(`Server running at http://localhost:${server.port}`)src/client.ts
Section titled “src/client.ts”import { html, render } from '@_bashell/slash'import { App } from './App'
const root = document.getElementById('app')if (root) { // Com HTML do servidor + script __SLASH_STATE__ na página, render() limpa o container // e renderiza no cliente (veja Hydration) render(html`<${App} />`, root)}Templates de Projeto
Section titled “Templates de Projeto”Slash fornece templates prontos para uso: SPA (aplicação no navegador), SSR (renderização por requisição no servidor) e SSG (site estático gerado no build).
Template SPA (slash-spa)
Section titled “Template SPA (slash-spa)”# Clone o templategit clone https://github.com/bashell-rrocha/slash-spa my-appcd my-app
# Instale dependênciasbun install
# Execute em desenvolvimentobun run dev
# Build para produçãobun run buildLocalização: bashell-rrocha/slash-spa
Template SSR (slash-ssr)
Section titled “Template SSR (slash-ssr)”# Clone o templategit clone https://github.com/bashell-rrocha/slash-ssr my-ssr-appcd my-ssr-app
# Instale dependênciasbun install
# Execute servidor de desenvolvimentobun run dev
# Build e serve em produçãobun run buildbun run startLocalização: bashell-rrocha/slash-ssr
Template SSG (slash-ssg)
Section titled “Template SSG (slash-ssg)”Use quando o conteúdo é conhecido no build: uma página HTML por URL, imagens otimizadas (AVIF, WebP e JPEG responsivos), CSS Modules e ilhas interativas hidratadas só onde necessário. A saída fica em dist/ e funciona em qualquer hospedagem estática. Veja Geração Estática (SSG).
# Clone o templategit clone https://github.com/bashell-rrocha/slash-ssg my-sitecd my-site
# Instale dependênciasbun install
# Desenvolvimento com live reloadbun run dev
# Build de produção em dist/bun run buildEstrutura de pastas:
public/ copiado como está para dist/ (index.html é a casca do documento)src/routes.ts lista de rotassrc/site.ts configuração do sitesrc/pages/ funções que retornam o HTML de cada páginasrc/islands/ componentes interativossrc/assets/images imagens processadas pelo pipelinesrc/lib/ núcleo do template (head, imagens, ilhas, prerender)scripts/ build, dev, previewScripts:
| Comando | O que faz |
|---|---|
bun run dev | Build em modo dev + servidor com live reload (observa src/ e public/) |
bun run build | Build de produção em dist/ |
bun run preview | Serve o dist/ já gerado |
bun run test | Testes unitários e de build |
bun run test:e2e | Testes de ponta a ponta com Playwright (faz o build e sobe o preview) |
A porta padrão é 4000; mude com PORT=4100 bun run dev (vale também para preview e test:e2e).
Localização: bashell-rrocha/slash-ssg
Build Setup
Section titled “Build Setup”Com Bun (Recomendado)
Section titled “Com Bun (Recomendado)”Bun tem suporte nativo para Slash através do export "bun" no package.json:
{ "exports": { ".": { "bun": "./src/index.ts", "import": "./dist/index.mjs" } }}Quando usar Bun como runtime, o source TypeScript é carregado diretamente sem build.
Com Vite
Section titled “Com Vite”bun add -D viteimport { defineConfig } from 'vite'
export default defineConfig({ esbuild: { jsxFactory: 'h', jsxFragment: 'Fragment', jsxInject: `import { h } from '@_bashell/slash'` }})Com esbuild
Section titled “Com esbuild”bun add -D esbuildimport * as esbuild from 'esbuild'
await esbuild.build({ entryPoints: ['src/main.ts'], bundle: true, outfile: 'dist/bundle.js', format: 'esm', target: 'es2022'})Verificação da Instalação
Section titled “Verificação da Instalação”Crie um arquivo de teste para verificar se tudo está funcionando:
import { h, html, createState, render } from '@_bashell/slash'
console.log('✅ Imports OK')
const state = createState(42)console.log('✅ State created:', state.get())
const element = html`<div>Hello Slash!</div>`console.log('✅ HTM working:', element)
const hElement = h('div', null, 'Hello from h()')console.log('✅ Hyperscript working:', hElement)Execute:
bun run test.tsSaída esperada:
✅ Imports OK✅ State created: 42✅ HTM working: [object HTMLDivElement]✅ Hyperscript working: [object HTMLDivElement]Segurança
Section titled “Segurança”O Slash é seguro por padrão: toda string é escapada, URLs perigosas e handlers que não são função são bloqueados. Leia a página Segurança antes de colocar dado de usuário numa página, e use sempre serializeStateForScript para embutir estado em <script>.
Troubleshooting
Section titled “Troubleshooting”Erro: Cannot find module ’@_bashell/slash’
Section titled “Erro: Cannot find module ’@_bashell/slash’”Solução: Verifique se a instalação foi concluída:
bun installErro: TypeScript não reconhece tipos
Section titled “Erro: TypeScript não reconhece tipos”Solução: Adicione "types": ["bun-types"] no tsconfig.json e rode:
bun install @types/bun --devErro: htm template not working
Section titled “Erro: htm template not working”Solução: Certifique-se de importar html de @_bashell/slash:
import { html } from '@_bashell/slash'Performance ruim em desenvolvimento
Section titled “Performance ruim em desenvolvimento”Solução: Use Bun para desenvolvimento (carrega TypeScript diretamente):
bun run src/main.tsPróximos Passos
Section titled “Próximos Passos”Agora que seu ambiente está configurado, aprenda a:
- Renderização Básica - Criar e renderizar elementos
- Sistema de Estado - Gerenciar estado reativo
- Componentes - Construir componentes reutilizáveis