nuxt 静态文件配置_如何在静态Nuxt应用程序中使用平面文件数据

本文介绍了如何在Nuxt静态应用中使用平面文件数据库替代API来存储和检索动态数据,以此节省服务器成本并提升性能。平面文件数据库通过JSON文件存储数据,简化了数据管理,但在安全性方面有所欠缺。在Nuxt中,可以通过动态导入JSON文件并自定义解码方法来实现平面文件数据库的使用。在构建时,可以使用Node.js脚本生成数据库,并在Nuxt构建前运行该脚本。
摘要由CSDN通过智能技术生成

nuxt 静态文件配置

Making your Nuxt web app static can potentially save you the time and money of setting up a server-rendered app. It may also offer superior performance.

将Nuxt Web应用程序设为静态可以潜在地节省您设置服务器呈现的应用程序的时间和金钱。 它还可能提供出色的性能。

But what if your app needs dynamic data? The most popular solution is to set up an API alongside your static app that can deliver dynamic data via AJAX.

但是,如果您的应用程序需要动态数据怎么办? 最受欢迎的解决方案是在您的静态应用程序旁边设置一个API,该API可以通过AJAX传递动态数据。

In this article, I'll show you another possible architecture - using a flat-file database. This architecture might save you the hassle of setting up an API and offers superior performance.

在本文中,我将向您展示另一种可能的体系结构-使用平面文件数据库。 这种架构可能会节省您设置API的麻烦,并提供卓越的性能。

什么是平面文件数据库? (What is a flat-file database?)

A "flat-file database" is a database architecture where data is stored in a simple text file rather than in database software like MySQL or MongoDB.

“平面文件数据库”是一种数据库体系结构,其中数据存储在简单的文本文件中,而不是存储在MySQL或MongoDB之类的数据库软件中。

In a Nuxt app, this file can be a JSON file that sits in your static files directory and is deployed alongside the markup files.

在Nuxt应用程序中,此文件可以是JSON文件,位于您的静态文件目录中,并且与标记文件一起部署。

At runtime, the JSON file is loaded by the Nuxt app. Once the data is parsed as JavaScript data it can be used to power the app.

在运行时,JSON文件由Nuxt应用程序加载。 数据解析为JavaScript数据后,就可以为应用程序供电。

为什么要使用平面文件数据库? (Why use a flat-file database?)

Flat-file databases are advantageous because of their simplicity and low overhead. But they are also insecure and don't offer the performance benefits of conventional database software, which is why they're rarely used.

平面文件数据库由于其简单性和较低的开销而具有优势。 但是它们也不安全,不能提供常规数据库软件的性能优势,这就是为什么很少使用它们的原因。

In the context of Nuxt apps, though, they have another great advantage – they can be stored and accessed from static hosting.

但是,在Nuxt应用程序的上下文中,它们还有另一个很大的优势–可以从静态托管存储和访问它们。

Using a flat-file database may also have a performance advantage over an API service which will have a small latency overhead incurred when requests are processed by the server.

与API服务相比,使用平面文件数据库还可能具有性能优势,而API服务将在服务器处理请求时产生较小的延迟开销。

However, flat-file DBs won't always be appropriate to use, as they offer no security and are read-only while in production. This means you'll need to rebuild the site any time you want to write new data.

但是,平面文件DB并不总是适合使用,因为它们不提供安全性,并且在生产中是只读的。 这意味着您想在任何时候写入新数据都需要重建站点。

A type of data that is a good candidate for flat-file storage and retrieval is meta data. For example, on the Vue.js Developers blog, which I built with Nuxt, I use a flat-file database to store meta data about published posts.

元数据是一种适合平面文件存储和检索的数据类型。 例如,在我使用Nuxt构建的Vue.js开发人员博客上 ,我使用平面文件数据库来存储有关已发布帖子的元数据。

This allows me to easily access that data across the site, for example on the home page where the latest blog articles are displayed, and on the topics page which indexes posts based on topic tags applied (both shown below).

这使我可以轻松地在整个站点上访问该数据,例如,在显示最新博客文章的主页上,以及根据所应用的主题标签对帖子进行索引的主题页面上(如下所示)。

在Nuxt中实现平面文件数据库体系结构 (Implementing the flat-file database architecture in Nuxt)

Now let's see how to implement the flat-file database architecture in your own Nuxt site.

现在,让我们看看如何在自己的Nuxt站点中实现平面文件数据库体系结构。

Say we want to create a blog home page which show the latest published article like that on the Vue.js Developers blog.

假设我们要创建一个博客首页,以显示最新发布的文章,例如Vue.js Developers博客上的文章。

We'll begin by seeing how flat-file-sourced data gets used in the page, and then work backwards until we can see how the whole architecture works.

首先,我们将了解页面中使用平面文件源数据的方式,然后向后工作,直到了解整个体系结构的工作方式。

在页面中使用平面文件数据 (Using flat-file data in a page)

In our home page component, pages/index.vue, we'll import getArticleSummaries from a soon-to-be-created JavaScript module flatFileDb.

在我们的主页组件pages / index.vue中 ,我们将从即将创建JavaScript模块flatFileDb导入getArticleSummaries

This method will return a Promise containing the article summary data ready for use on the page.

此方法将返回一个Promise,其中包含准备好在页面上使用的文章摘要数据。

You can, of course, use this data at build time via asyncData, and at run time via the created hook.

当然,您可以在构建时通过asyncData使用此数据,并在运行时通过created钩子使用此数据。

pages/index.vue:

pages / index.vue

const { getArticleSummaries } from "@/assets/js/flatFileDb";

export default {
    data: () => ({
        articleSummaries: []
    }),
    async asyncData () {
        const articleSummaries = await getArticleSummaries();
        return { articleSummaries }
    },
    async created () {
        this.articleSummaries = await getArticleSummaries();
    }
}

Note that the data structure we'll get from getArticleSummaries will be an array of objects like this:

请注意,我们将从getArticleSummaries获得的数据结构将是这样的对象数组:

[
    {
        title: "...",
        description: "...",
        published: "...",
        ...
    },
    ...
]

Note: If you have multiple entities (for example, in addition to articles you also store information about videos), each will have its own flat file and its own retrieval method in the app, like getVideoSummaries.

注意:如果您有多个实体(例如,除了文章之外,您还存储有关视频的信息),则每个实体在应用程序中都将具有自己的平面文件和自己的检索方法,例如getVideoSummaries

平面文件数据库模块 (Flat-file database module)

We saw above that a getArticleSummary method was imported from the flatFileDb module. Let's see how we can implement that.

上面我们看到,从flatFileDb模块导入了getArticleSummary方法。 让我们看看如何实现它。

Our flat-file database will be included in our static files and should be a JSON file since these are simple to parse as valid JavaScript data.

我们的平面文件数据库将包含在我们的静态文件中,并且应该是JSON文件,因为它们很容易解析为有效JavaScript数据。

We'll include this JSON file by using a dynamic import. This feature is designed for importing JavaScript modules, but it works with JSON files out-of-the-box with Webpack. Conveniently, you get the JSON file already parsed as JavaScript.

我们将通过动态导入来包含此JSON文件。 此功能是为导入JavaScript模块而设计的,但可与Webpack开箱即用地使用JSON文件一起使用。 方便地,您已经将JSON文件解析为JavaScript。

It's important to call the dynamic import in a try/catch block to prevent the app crashing if the file is missing or the JSON parsing fails.

try/catch块中调用动态导入很重要,以防止文件丢失或JSON解析失败时应用程序崩溃。

Before we return the data to the consuming component we need to "decode" it with another custom method decodeArticleSummaries. I'll explain that in a moment.

在将数据返回到使用方组件之前,我们需要使用另一个自定义方法decodeArticleSummaries “解码”它。 我会在稍后解释。

Finally, note that a JSON file doesn't have a default export, so you'll need to access the default property of the db module to access the data.

最后,请注意,JSON文件没有默认导出,因此您需要访问db模块的default属性以访问数据。

assets/js/flatFileDb.js:

asset / js / flatFileDb.js

import { decodeArticleSummaries } from "dbDecoders";

const getArticleSummaries = async () => {
    try {
    const db = await import(`@/static/article-summaries.json`);
    return decodeArticleSummaries(db.default);
  } catch (err) {
    console.log(err);
    return [];
  }
};

export { getArticleSummaries };

解码数据库 (Decoding the database)

Above, I said the data provided to the component would look like this:

上面,我说过提供给组件的数据如下所示:

{
    title: "...",
    description: "...",
    published: "...",
    // etc
}

However, it shouldn't be stored in the database like this because the property names are wastefully long.

但是,不应将其存储在这样的数据库中,因为属性名称太浪费了。

In order to keep the flat file as lean as possible we should "encode" each key when the database is created. Then we should decode them before they're consumed by components so they have their full names available to the developer.

为了使平面文件尽可能的精简,我们应该在创建数据库时对每个密钥进行“编码”。 然后,我们应该在组件使用它们之前对其进行解码,以便开发人员可以使用它们的全名。

So, let's say we make "title" => "t", "description" => "d", and "published" => "p". In a large database, this transformation could reduce the file size by many bytes.

因此,假设我们使“ title” =>“ t”,“ description” =>“ d”和“ published” =>“ p”。 在大型数据库中,此转换可以将文件大小减少许多字节。

assets/js/dbDecode.js:

资产/js/dbDecode.js

const decodeArticleSummaries = db => {
    return db.map(article => ({
        title: article.t,
        description: article.d,
        published: article.p
        // etc
    }));
}

生成平面文件数据库 (Generating the flat-file database)

So now we've seen how the flat-file database is consumed at run time. How is it created?

现在,我们已经了解了运行时如何使用平面文件数据库。 它是如何创建的?

You could create a flat-file database manually by hand, but usually you'll want to generate it at build time with a Node.js script.

您可以手动创建一个平面文件数据库,但是通常您希望在构建时使用Node.js脚本生成它。

In our example, we'll want to make a script that extracts the meta data of each article and stores it as static/article-summaries.json. Let's assume the articles are stored as markdown and are in an "articles" directory in the project root.

在我们的示例中,我们将要创建一个脚本,以提取每篇文章的元数据并将其存储为static / article-summaries.json 。 假设文章存储为markdown,并且位于项目根目录下的“ articles”目录中。

The details of the script will be specific to your implementation, so I'll just give you pseudo code to communicate the basic idea.

该脚本的详细信息将特定于您的实现,因此,我仅向您提供伪代码以传达基本思想。

scripts/generateDb.js:

脚本/generateDb.js

const fs = require("fs");
const frontmatterExtractor = require("./frontmatterExtractor");
const encodeArticleSummaries = require("./encodeArticleSummaries");

module.exports = async () => {
    // Load article files
    const articles = await fs.readdir("/articles", (err, filePaths) => {
        // Create the database by reading each file
        const db = filePaths.map(async path => {
            const file = await fs.readFile(path);
            // Extract the meta data
            return frontmatterExtractor(file);
        });
        // Encode the data
        const encoded = encodeArticleSummaries(db);
        // Write the database object to a JSON file
        await fs.writeFile(
            "/static/article-summaries.json", 
            JSON.stringify(encoded)
        );
    });
}

在网站构建之前运行数据库生成器脚本 (Running the DB generator script before the site build)

Now that we've got a database generator script, let's trigger it to run just before the build (or generate) processes which will want to consume it.

现在我们有了数据库生成器脚本,让我们触发它在要使用它的构建(或生成)进程之前运行。

To do this, we'll squeeze it into the NPM commands in package.json. Note that by using the && operator we can ensure the Nuxt process doesn't begin until the generator script completes.

为此,我们将其压缩到package.json中的NPM命令中。 请注意,通过使用&&运算符,我们可以确保在生成器脚本完成之前Nuxt进程不会开始。

package.json:

package.json

{
    ...
    "scripts": {
        ...
        "build": "node scripts/generateDb && nuxt build",
        "generate": "node scripts/generateDb && nuxt generate",
        ...
    }
    ...
}

In development, however, I find it easier to manually generate the database on the command line whenever I need to update it:

但是,在开发中,我发现在需要更新时在命令行上手动生成数据库更加容易:

$ node scripts/generateDb

进一步阅读 (Further reading)

That's the basic architecture explained. Here are a few other articles learn more:

这就是解释的基本架构。 这是其他一些文章,以了解更多信息:

翻译自: https://www.freecodecamp.org/news/how-to-use-flat-file-data-in-a-static-nuxt-app/

nuxt 静态文件配置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值