Skip to main content

Ghi nhanh

Ghi chú những điều cần nhớ, rút ra được trong quá trình thực nghiệm, chặng đường tiếp cận với tri thức! Ghi lại như 1 kinh nghiệm để tránh mắc sai lầm và những phương án có thể áp dụng để giải quyết vấn đề bế tắc!

Cần nhớ: tham số:

"slug" trong front matter để tùy chỉnh link bài đăng.
"hide_table_of_contents": true" để ẩn mục lục

Bạn có thể kích hoạt tính năng UI thú vị này để tự động ẩn thanh điều hướng khi người dùng bắt đầu cuộn xuống trang và hiển thị lại khi người dùng cuộn lên.

docusaurus.config.js

export default {
  themeConfig: {
    navbar: {
      hideOnScroll: true,
    },
  },
};

Edit lại giao diện "Blog" bằng cách edit lại file: "index.js" (link: "src\theme\BlogListPage\index.js") 27/11/2024

CẦN LƯU Ý: Tên file.md tránh dùng Tiếng Việt và phải dùng định dạng không được khoảng trắng, không dấu(ví dụ:"tim-hieu-logseq.md", "ve-github.md"... )> Không đúng qui ước này plugin "docusaurus-plugin-generate-index"sẽ không xuất ra được link file dẫn đến trang web cần truy cập trong file "docs/index.md"

THÊM LƯU Ý: Tên Folder trong Docusaurus không được có khoảng trắng, nếu không sẽ gây lỗi khi render đề mục file.

CHÚ Ý: Để cập nhật version mới "Docurausus"(Update available 3.6.1 → 3.6.3) ta gõ lệnh sau từ Terminal:

npm i @docusaurus/core@latest @docusaurus/plugin-ideal-image@latest @docusaurus/preset-classic@latest
       @docusaurus/remark-plugin-npm2yarn@latest @docusaurus/module-type-aliases@latest @docusaurus/types@latest

CHÚ Ý:

FILE "plugins/docusaurus-plugin-generate-index.js" trích được nhiều đề mục bài viết nhất để đưa vào "docs/index.md" và các đề mục đúng link:

const fs = require('fs');
const path = require('path');

// Hàm chuẩn hóa tên file (chuyển không dấu, thay khoảng trắng thành '-')
function normalizeFileName(fileName) {
    return fileName
        .normalize('NFD') // Chuẩn hóa Unicode
        .replace(/[\u0300-\u036f]/g, '') // Loại bỏ dấu
        .replace(/\s+/g, '-') // Thay khoảng trắng bằng dấu '-'
        .toLowerCase();
}

// Hàm trích xuất tiêu đề từ nội dung file
function extractTitle(filePath) {
    try {
        const fileContent = fs.readFileSync(filePath, 'utf8');
        const titleMatch = fileContent.match(/^#\s(.+)/); // Trích tiêu đề từ dòng đầu tiên có dạng `# Tiêu đề`
        return titleMatch ? titleMatch[1].trim() : null; // Nếu có tiêu đề, trả về tiêu đề
    } catch (error) {
        console.error(`Lỗi khi đọc file: ${filePath}`, error);
        return null; // Trả về null nếu gặp lỗi
    }
}

// Hàm tạo danh sách index
function generateIndex(dirPath, basePath = '', output = []) {
    const items = fs.readdirSync(dirPath, { withFileTypes: true });

    items.forEach((item) => {
        const fullPath = path.join(dirPath, item.name);
        if (item.isDirectory()) {
            // Nếu là thư mục, đệ quy xử lý
            generateIndex(fullPath, path.join(basePath, item.name), output);
        } else if (item.name.endsWith('.md') || item.name.endsWith('.mdx')) {
            const title = extractTitle(fullPath); // Trích tiêu đề
            const label = title || normalizeFileName(item.name.replace(/\.mdx?$/, '')); // Dùng tiêu đề nếu có, hoặc tên file đã normalize
            const relativePath = path.join('docs', basePath, item.name).replace(/\\/g, '/'); // Thêm 'docs/' vào đường dẫn
            output.push(`- [${label}](${relativePath})`);
        }
    });

    return output;
}

// Xuất plugin
module.exports = function (context, options) {
    return {
        name: 'generate-index-plugin',
        async loadContent() {
            const docsDir = path.join(context.siteDir, 'docs');
            const outputFile = path.join(docsDir, 'index.md');

            const content = `---\ntitle: Index of All Articles\nslug: /\n---\n\n# Index of All Articles\n\n`;
            const indexEntries = generateIndex(docsDir);

            fs.writeFileSync(outputFile, content + indexEntries.join('\n'));
            console.log('Index page updated at:', outputFile);
        },
    };
};

Ghi nhanh ngày 07/12/2024

Để có chỉ mục "label+link" đủ mọi đề mục file trong Website và xuất ra "docs/index.md" ta cần bổ sung và kích hoạt các phần này:

1)dán code vào "plugins/docusaurus-plugin-generate-index.js"

const fs = require('fs');
const path = require('path');

// Hàm chuẩn hóa tên file (chuyển không dấu, thay khoảng trắng thành '-')
function normalizeFileName(fileName) {
    return fileName
        .normalize('NFD') // Chuẩn hóa Unicode
        .replace(/[\u0300-\u036f]/g, '') // Loại bỏ dấu
        .replace(/\s+/g, '-') // Thay khoảng trắng bằng dấu '-'
        .toLowerCase();
}

// Hàm trích xuất tiêu đề từ nội dung file
function extractTitle(filePath) {
    try {
        const fileContent = fs.readFileSync(filePath, 'utf8');
        const titleMatch = fileContent.match(/^#\s(.+)/); // Trích tiêu đề từ dòng đầu tiên có dạng `# Tiêu đề`
        return titleMatch ? titleMatch[1].trim() : null; // Nếu có tiêu đề, trả về tiêu đề
    } catch (error) {
        console.error(`Lỗi khi đọc file: ${filePath}`, error);
        return null; // Trả về null nếu gặp lỗi
    }
}

// Hàm tạo danh sách index
function generateIndex(dirPath, basePath = '', output = []) {
    const items = fs.readdirSync(dirPath, { withFileTypes: true });

    items.forEach((item) => {
        const fullPath = path.join(dirPath, item.name);
        if (item.isDirectory()) {
            // Nếu là thư mục, đệ quy xử lý
            generateIndex(fullPath, path.join(basePath, item.name), output);
        } else if (item.name.endsWith('.md') || item.name.endsWith('.mdx')) {
            const title = extractTitle(fullPath); // Trích tiêu đề
            const label = title || normalizeFileName(item.name.replace(/\.mdx?$/, '')); // Dùng tiêu đề nếu có, hoặc tên file đã normalize
            const relativePath = path.join('docs', basePath, item.name).replace(/\\/g, '/'); // Thêm 'docs/' vào đường dẫn
            output.push(`- [${label}](${relativePath})`);
        }
    });

    return output;
}

// Xuất plugin
module.exports = function (context, options) {
    return {
        name: 'generate-index-plugin',
        async loadContent() {
            const docsDir = path.join(context.siteDir, 'docs');
            const outputFile = path.join(docsDir, 'index.md');

            const content = `---\ntitle: Index of All Articles\nslug: /\n---\n\n# Index of All Articles\n\n`;
            const indexEntries = generateIndex(docsDir);

            fs.writeFileSync(outputFile, content + indexEntries.join('\n'));
            console.log('Index page updated at:', outputFile);
        },
    };
};

2)khai báo để kích hoạt plugin này trong file: "docusaurus.config.js" ở phần "plugins" Bổ túc giòng này vào:

require.resolve('./plugins/docusaurus-plugin-generate-index'),

3)Cài "src/utils/parseMarkdown.ts"

4)Biên tập file: "src/pages/navigation.tsx"

5)Khai báo kích hoạt trong file "docusaurus.config.js"

[
      require.resolve('./plugins/docusaurus-plugin-generate-index'),
      {
        output: 'static/indexData.json', // Đường dẫn mong muốn
        docsDir: './docs', // Thư mục chứa tài liệu
      },
    ],

Bổ túc khai báo:

const marked = require('marked');

Nếu cần update "marked":

npm update marked

6)Install "marked" bằng cách gõ trong Terminal:

npm install marked