Skip to main content

PUG

PUG

image.png

PUG (ранее: Jade) - высокопроизводительный шаблонизатор HTML разметки.

Этот проект ранее был известен как "Jade". Однако разработчикам стало известно, что "Jade" является зарегистрированной торговой маркой; в результате потребовалось переименование. После некоторого обсуждения среди сопровождающих в качестве нового имени для этого проекта было выбрано "Pug" . Начиная с версии 2, "pug" является официальным именем пакета.


Основные ресурсы

Vite: https://vite.dev/

TypeScript: https://www.typescriptlang.org/

 

PUG JavaScript:

Основная документация JavaScript (может потребоваться VPN) : https://pugjs.org/api/getting-started.html
Основной репозиторий JavaScript кода: https://github.com/pugjs/pug

PUG PHP:

Основная документация для транспайлера PHP: https://www.phug-lang.com/
Основной репозиторий для PHP: https://github.com/pug-php/pug


Инсталляция

Разворачиваем каркас приложения

Для установки необходимо наличие служб Node.JS и NPM. 
В примерах производится установка на версиях:
node - 21.7.3
npm - 10.5.0

Инициализируем установку шаблона приложение, с помощью движка Vite.

npm create vite@latest . -- --template vanilla-ts

Устанавливаем зависимости.
После установки зависимостей (пакеты библиотек) в проекте появится папка /node_modules 

npm install

Делаем тестовый запуск.

npm run dev

image.png

Следующий шагом необходимо привести файл package.json к следующему виду:

Добавляются следующие библиотеки и решения: веб-сервер express, htmx, pino логгер, типы для typescript, плагин pug, sass-препроцессор css, плагин для инъекций в приложение.

{
  "name": "any-project-name",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "description": "",
  "author": "",
  "license": "ISC",
  "main": "index.js",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview",
    "lint": "eslint .",
    "lint:fix": "eslint . --fix"
  },
  "dependencies": {
    "express": "^4.18.2",
    "htmx.org": "^2.0.1",
    "pino": "^8.19.0",
    "pino-colada": "^2.2.2",
    "pino-pretty": "^10.3.1"
  },
  "devDependencies": {
    "@antfu/eslint-config": "^2.6.4",
    "@rollup/plugin-inject": "^5.0.5",
    "@rushstack/eslint-patch": "^1.7.2",
    "@types/glob": "^8.1.0",
    "@types/node": "^20.11.13",
    "@types/pino": "^7.0.5",
    "@types/pug": "^2.0.10",
    "@typescript-eslint/eslint-plugin": "^6.20.0",
    "@typescript-eslint/parser": "^6.20.0",
    "eslint": "^8.56.0",
    "glob": "^10.4.2",
    "lint-staged": "^15.2.1",
    "pug": "^3.0.2",
    "sass": "^1.70.0",
    "sass-loader": "^14.1.0",
    "typescript": "~5.6.2",
    "vite": "^5.4.10",
    "vite-plugin-pug": "^0.3.2"
  }
}

Повторно запустить процесс добавление зависимостей.

npm install

Удаляем все файлы из папки /src

Модифицируем файл tsconfig.json следующими правками:

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ESNext", "DOM", "DOM.Iterable"],
    "skipLibCheck": true,
    "baseUrl": ".",

    /* Bundler mode */
    "moduleResolution": "Bundler",
    "paths": {
      "@/*": ["src/*"],
      "@/assets": ["src/assets/*"],
      "@/components": ["src/components/*"],
      "@/models": ["src/models/*"],
      "@/pages": ["src/pages/*"],
      "@/plugins": ["src/plugins/*"],
      "@/scripts": ["src/scripts/*"],
      "@/libs": ["src/libs/*"]
  },
    "allowImportingTsExtensions": true,
    "isolatedModules": true,
    "moduleDetection": "force",

    /* Linting */
    "strict": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noEmit": true,

  },
  "references": [{ "path": "./tsconfig.node.json" }],
  "include": ["src", "src/**/*.ts", "src/**/*.tsx"],
  "exclude": ["node_modules"],
  "types": ["vite/client"],
}

Добавляем файл tsconfig.node.json в корень проекта, со следующим содержанием:

{
    "compilerOptions": {
        "composite": true,
        "module": "ESNext",
        "moduleResolution": "bundler",
        "allowSyntheticDefaultImports": true,
        "skipLibCheck": true
    },
    "include": ["vite.config.ts"]
}

Добавляем файл .prettierrc в корень проекта, со следующим содержанием:

{
    "semi": true,
    "singleQuote": true,
    "bracketSpacing": true,
    "trailingComma": "all",
    "printWidth": 80,
    "tabWidth": 4,
    "arrowParens": "always",
    "endOfLine": "lf"
}

Добавляем файл eslint.config.js в корень проекта, со следующим содержанием:

import antfu from '@antfu/eslint-config';

export default antfu({
    rules: {
        curly: 'off',
        'antfu/consistent-list-newline': 'off',
        'antfu/if-newline': 'off',
        'import/newline-after-import': 0,
        'no-console': 'off',
        'style/arrow-parens': 'off',
        'style/brace-style': 'off',
        'style/indent': 'off',
        'style/operator-linebreak': 'off',
        'style/spaced-comment': 'off',
    },
    typescript: true,
    yaml: false,
    stylistic: {
        semi: true,
        indent: 4,
        quotes: 'single',
    },
    ignores: ['public/', 'node_modules/', 'dist/', 'build/', 'bruno/'],
});

Добавляем файл vite.config.ts в корень проекта, со следующим содержанием:

 

 


Файловая структура проекта

В этой секции изложены основные требования к содержанию и ведению файловой структуры любого проекта в котором используется этот шаблонизатор.


Блоки (Blocks)

Блок


Частицы (Partials)

Частица


Компоненты (Components)

Компонент


Примеси (Mixins)

Примеси (Миксины) -


FAQ

Основные ошибки и способы их устранения.