Вернуться назад

Hello World!

Ура!!

# Структура проекта:

my-fullstack-app/
├── backend/
│   └── server.js
├── frontend/
│   ├── index.html
│   ├── package.json
│   ├── vite.config.js
│   └── src/
│       ├── components
│       │   └── Govno.vue
│       ├── App.vue
│       ├── main.js
│       └── style.css
└── package.json

Backend

Для начала установим Express:


mkdir my-fullstack-app
cd my-fullstack-app

# Создаём package.json:
npm init -y

# Устанавливаем express:
npm install express

Создадим файл server.js:

// backend/server.js

import express from "express";

const app = express();
const PORT = 3000;

app.get("/", (req, res) => {
    res.send("kakashka");
});

app.get("/api/hello", (req, res) => {
    res.json({ message: "Это сраное сообщение. Ты рад, что его получил?" });
});

app.listen(PORT, () => {
    console.log(`Сервер запущен на порту ${PORT}`);
});

Чтобы импорты нормально работали, нам нужно указать в файле package.json тип: module.

// package.json

{
  "name": "my-vue-app3",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  // Здесь указываем тип:
  "type": "module",
  "dependencies": {
    "express": "^5.1.0"
  }
}

Frontend

Устанавливаем Vue:

# Создаём проект в папке frontend ...
# ... и передаём create-vite в качестве аргумента: --template vue:
npm create vite@latest frontend -- --template vue
cd frontend
npm install
cd ..

Более подробное объяснение

lala

# Находит пакет create-vite (т.е. тот, у которого имя начинается с create-):
npm create vite@latest frontend -- --template vue

# То же самое:
npx create-vite@latest frontend --template vue

# То есть, по сути, npm create = npx create-…

# Можно установить пакет create-vite вручную (глобально):
npm install -g create-vite
create-vite frontend --template vue

# Можно установить локально:
npm install create-vite --save-dev
npx create-vite frontend --template vue
npm uninstall create-vite

# То есть следующая строка это то же самое, что и предыдущие три:
npx create-vite@latest frontend --template vue

# pnpm
pnpm add create-vite --save-dev
pnpm exec create-vite frontend --template vue
pnpm remove create-vite
# Или в одной строке:
pnpm create vite@latest frontend -- --template vue
# Это просто удобная обёртка над:
pnpm dlx create-vite@latest frontend --template vue

# yarn
yarn add create-vite --dev
yarn create vite frontend --template vue
yarn remove create-vite

Чтобы во время разработки запросы /api/... шли на мой сервер Express, а не блокировались браузером (CORS), нужно добавить прокси:

// vite.config.js

// импортируем defineConfig:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  // добавляем прокси:
  server: {
    proxy: {
      '/api': 'http://localhost:3000',
    },
  },
})
// frontend/src/main.js

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'

createApp(App).mount('#app')
<!-- frontend/src/App.vue -->

<script setup>
  import Govno from './components/Govno.vue'
</script>

<template>
  <Govno />
</template>

<style scoped>
  /* Здесь пока ничего нет */
</style>
<!-- frontend/src/components/Govno.vue -->

<script setup>
    import { ref, onMounted } from "vue";
    
    const myCount = ref(0);
    const message = ref("Загрузка ...");

    onMounted(async () => {
        const res = await fetch('/api/hello')
        const data = await res.json()
        message.value = data.message
    });
</script>

<template>
    <h1 class="under_govno">Шаблон</h1>
    <div>Счётчик: {{ myCount }}</div>
    <div>
        <button v-on:click="myCount++">Кнопка</button>
    </div>
    <div>
        <p>Сообщение от сервера: {{ message }}</p>
    </div>
</template>

<style scoped>
    .under_govno {
        text-decoration: underline
    }
</style>

Запускаем backend-сервер на порту 3000:

node backend/server.js

Запускаем сервер для Vue на порту 5173:

# Если нужно раздавать файлы из текущей папки:
npm run dev

# Если нужно указать папку:
npm run dev --prefix frontend

# pnpm
pnpm --dir frontend run dev
# Запустить раздачу файлов из frontend/dist:

pnpm dlx serve frontend/dist