nuxt.js的核心代码
by Krutie Patel
通过克鲁蒂·帕特尔(Krutie Patel)
Are you new to the Nuxt.js framework and totally overwhelmed by the number of folders it comes with? Are you also surprised that most of them are empty with just the readme file in them? Well, that’s where I was little over a year ago. Since then, I’ve always wanted to learn and document the magic that each folder brought into the Nuxt project.
您是Nuxt.js框架的新手,并且对它附带的文件夹数量感到不知所措吗? 您是否也对其中大多数文件都为空,而其中仅包含自述文件感到惊讶? 好吧,那是我一年多以前的地方。 从那时起,我一直想学习并记录每个文件夹带入Nuxt项目的魔力。
And now, after implementing a few projects with this framework, I have documented my understanding of how these folders work together to bring the server-rendered Vue application to life.
现在,在使用此框架实施了一些项目之后,我记录了对这些文件夹如何协同工作以使服务器渲染的Vue应用程序栩栩如生的理解。
The diagram above is based on Vue SSR guide, and extended with Nuxt.js in mind. At a glance, you see different folders in Your universal application code section, and how the code is then, packaged by Nuxt and bundled by Webpack.
上图基于Vue SSR指南 ,并在扩展时考虑了Nuxt.js。 一目了然,您会在“通用应用程序代码”部分中看到不同的文件夹,以及如何通过Nuxt打包并通过Webpack打包代码。
This article is neither tutorial nor complete guide to Nuxt SSR. It rather shows what goes into universal application.
本文既不是教程,也不是Nuxt SSR的完整指南。 而是显示了通用应用程序中的内容。
Although you see modules, serverMiddleware, and plugins at the top of the diagram, let’s start with Store first.
尽管您在图的顶部看到模块,serverMiddleware和插件,但让我们先从Store开始。
Nuxt comes pre-packaged with Vuex, but it’s not activated unless you make a Vuex store in the /store directory and create the store.
Nuxt预先与Vuex打包在一起,但是除非您在/ store目录中创建Vuex商店并创建商店,否则它不会被激活。
This is very special directory for any data-driven project. This is where you can create a data-store, as well as define the nuxtServerInit action. This happens to be the very first lifecycle hook as well!
对于任何数据驱动的项目,这都是非常特殊的目录。 在这里您可以创建数据存储,以及定义nuxtServerInit操作。 这恰好也是第一个生命周期挂钩!
const createStore = () => { return new Vuex.Store({ ... })}
When the user initially accesses your application, this helps fill/update the store. It also maintains the state of your data throughout the application.
当用户最初访问您的应用程序时,这有助于填充/更新商店。 它还可以维护整个应用程序中数据的状态。
There are three different kinds of route middleware available in Nuxt. They are all defined in one central location — in the /middleware directory.
Nuxt提供了三种不同的路由中间件。 它们都在/ middleware目录的一个中央位置定义。
From here, you can use them in the following ways:
从这里,您可以通过以下方式使用它们:
// nuxt.config.js
export default { router: { middleware: 'authenticated' },}
// layouts/default.vue
export default { middleware: 'authenticated-basic-plan-user'}
// pages/index.vue
export default { middleware: 'subscribed'}
The middleware above are dealt in this exact order — meaning, their priorities are non-negotiable. So you must think through and plan your application carefully to get the most use out of them.
上面的中间件是按照确切的顺序处理的-这意味着它们的优先级是不可协商的。 因此,您必须仔细考虑并计划应用程序,以充分利用它们。
There are three directories where .vue files are created in a Nuxt project.
在Nuxt项目中创建三个目录的.vue文件。
This is the most important directory of all that houses application views and routes. Vue.js components created here are directly converted into application routes.
这是存放应用程序视图和路由的所有目录中最重要的目录。 此处创建的Vue.js组件直接转换为应用程序路由。
The real power of page components lies in dynamic routes. You can use them to generate SEO friendly and data-oriented URLs. Dynamic routes are generated based on your directory structure under /pages.
页面组件的真正力量在于动态路由。 您可以使用它们来生成SEO友好和面向数据的URL。 动态路由是根据/ pages下的目录结构生成的。
In addition, Nuxt adds three special methods on page components which aren’t available anywhere else. They are validate(), asyncData() & fetch().
另外,Nuxt在页面组件上添加了三种特殊方法,这些方法在其他任何地方都无法使用。 它们是validate() , asyncData()和fetch() 。
// pages/index.vue
export default {
validate() { // validates dynamic URL parameters // verifies the availability of the data }, asyncData() { // sets component data },
fetch() { // doesn't set component data, but // fetches further contextual data }
}
Layout components power the structural aspects of your application. Common components found on all pages are created here (like main menu, secondary menu, header, footer, etc.). They’re located in the /layouts directory.
布局组件为应用程序的结构方面提供了动力。 在此处创建所有页面上的通用组件(例如主菜单,辅助菜单,页眉,页脚等)。 它们位于/ layouts目录中。
You can be as creative as you want here, after all they are Vue.js components. Don’t forget to add <nuxt/> in the main content area of the layout.
它们毕竟是Vue.js组件,因此您可以在这里发挥自己的创造力。 不要忘记在布局的主要内容区域添加<nux t />。
<template> <div> <nuxt/> </div></template>
Incorporate route-middleware and store data-state with the layout component to build perfect who-sees-what features for any number of user-types with varied scenarios. You can achieve a bit more than just with a custom user interface.
将路由中间件与布局组件相结合,并存储数据状态 ,以针对各种场景下的任意数量的用户类型构建完善的“ 看谁看”功能。 您不仅可以通过自定义用户界面实现更多目标。
These are regular, but versatile Vue components. They are created under the /components directory. They are not supercharged with special methods like Page components.
这些是常规但通用的Vue组件。 它们在/ components目录下创建。 它们不会使用诸如Page组件之类的特殊方法来增强。
But they allow you to structure and organize your business logic. They also hide heavy markup from page and layout components. This makes your codebase more manageable.
但是它们允许您构造和组织业务逻辑。 它们还会在页面和布局组件中隐藏沉重的标记。 这使您的代码库更易于管理。
Now look closely — can you see the partial folder structure in this Nuxt lifecycle diagram?Hint: Store (nuxtServerInit), Route Middleware and Page components (validate, asyncData & fetch methods)
现在仔细观察-您可以在此Nuxt生命周期图中看到部分文件夹结构吗? 提示:存储(nuxtServerInit),路由中间件和页面组件(验证,asyncData和获取方法)
Assets such as JavaScript files, custom fonts, and CSS files are processed by Webpack using specific loaders (css-loader, file-loader, url-loader etc) depending upon file types. For example, if you write your CSS in .scss or .less format then Webpack will process these files using a specific loader and output compiled .css file that can be used by the browser.
Webpack使用特定的加载器(css-loader,file-loader,url-loader等)来处理JavaScript文件,自定义字体和CSS文件之类的资产,具体取决于文件类型。 例如,如果您以.scss或.less格式编写CSS,则Webpack将使用特定的加载器处理这些文件,并输出浏览器可以使用的已编译.css文件。
You can even customize your nuxt.config.js to instruct Webpack to minify and optimize images in the assets folder as a part of your build process. After Webpack processes the files, it attaches hash-code — for example, index.4258e3668a44556dd767.js — to the processed items which helps in long-term caching of dynamic assets and cache-busting.
您甚至可以自定义nuxt.config.js,以指示Webpack在构建过程中缩小和优化资产文件夹中的图像。 Webpack处理文件后,它将哈希码( 例如index.4258e3668a44556dd767.js)附加到已处理的项目,这有助于长期缓存动态资产和清除缓存。
For the assets that will not change, you can safely put them in the static folder. Webpack ignores the static folder and will not process anything in there.
对于不会更改的资产,您可以安全地将它们放在静态文件夹中。 Webpack会忽略静态文件夹,并且不会在其中处理任何内容。
They are all defined (by their path) in Nuxt configuration. They are accessible globally within the Nuxt application.
它们都是在Nuxt配置中定义的(通过它们的路径)。 在Nuxt应用程序中可以全局访问它们。
A fresh Nuxt application is pre-packaged with Vue, Vue Router, Vuex, Vue Server Rendered and Vue Meta by default.
默认情况下,新的Nuxt应用程序已预先打包有Vue,Vue路由器,Vuex,Vue服务器渲染和Vue Meta。
But you may wonder, what about features like Sitemap, Google Analytics, Progressive Web Apps, or more? If you’re thinking of using modules, then yes, you are right, this is where the power of Nuxt modules come into play.
但是您可能想知道,Sitemap,Google Analytics(分析),Progressive Web Apps或其他功能如何? 如果您正在考虑使用模块,那么是的,您是对的,这正是Nuxt模块发挥作用的地方。
serverMiddleware can be considered an extension point for your application. They are special because they have access to the underlying instance of the connect framework.
serverMiddleware可以被视为您的应用程序的扩展点。 它们之所以特别,是因为它们可以访问连接框架的基础实例。
Since Nuxt uses connect to deliver the application, it allows custom functions to be hooked into the underlying request pipeline as middleware.
由于Nuxt使用connect来交付应用程序,因此它允许将自定义函数作为中间件挂接到基础请求管道中。
You can use serverMiddleware to:
您可以使用serverMiddleware来:
Note that you don’t have any pre-populated empty folders for serverMiddleware and modules. You create them when needed.
请注意,对于serverMiddleware和模块,您没有任何预填充的空文件夹。 您可以在需要时创建它们。
You can make your existing Vue mixins, filters, or directives work harder just by converting them into Nuxt plugins. You place them in the /plugins directory that comes with a fresh Nuxt installation.
您只需将现有的Vue mixin,过滤器或指令转换为Nuxt插件,就可以使其工作更加困难。 您可以将它们放在新安装的Nuxt随附的/ plugins目录中。
But most of the time, you will end up adding external packages or Vue libraries as Nuxt plugins. You incorporate them in Nuxt by simply using Vue.use() syntax. Some of the staple plugins I always end up using in my Nuxt implementation are Vue Bootstrap, form validation, font-awesome icon-set and axios.
但是大多数时候,您最终会添加外部软件包或Vue库作为Nuxt插件。 您只需使用Vue.use()语法将它们合并到Nuxt中。 我经常在Nuxt实现中最终使用的一些主要插件是Vue Bootstrap,表单验证,超棒的图标集和axios。
That’s not the end of plugins. You can write custom plugins and add them in the application root. They are available globally in your Nuxt application. This is my personal favorite way of adding custom GreenSock or Scroll-Magic transitions into the project, and using them in the Vue (/components) and Page (/pages) components.
插件还没有结束。 您可以编写自定义插件并将其添加到应用程序根目录中。 它们在您的Nuxt应用程序中全局可用。 这是我个人最喜欢的将自定义GreenSock或Scroll-Magic过渡添加到项目中,并在Vue (/组件)和Page (/ pages)组件中使用它们的方式。
Once you have the desired features in place, you build your application using npm run build. Nuxt packages your application.
具备所需功能后,即可使用npm run build来构建应用程序。 Nuxt打包您的应用程序。
As shown in the diagram below, index.js is the main entry point, which imports app.js.
如下图所示, index.js是导入app.js的主要入口点。
App.js defines the root Vue instance. If you look closely in .nuxt/App.js, it’s nothing but a Vue component.
App.js定义了根Vue实例。 如果您仔细查看.nuxt / App.js ,那么它就是Vue组件。
Once this root Vue instance is defined, client entry (client.js) creates a new instance based on it and mounts it to the DOM element. End-users see a fresh instance of an app in their browsers. While server entry (server.js) creates a new app instance for each request.
定义此根Vue实例后,客户端条目( client.js )将基于该实例创建一个新实例,并将其安装到DOM元素。 最终用户会在浏览器中看到一个应用程序的新实例。 服务器条目( server.js )为每个请求创建一个新的应用程序实例。
And finally, Webpack bundles your app so that the code runs on both the client and server side. The server bundle renders the server side, and the client bundle hydrates static HTML markup in the browser. It turns it into a dynamic DOM that can react to client-side data changes.
最后,Webpack捆绑了您的应用程序,以使代码在客户端和服务器端均可运行。 服务器捆绑包呈现服务器端,而客户端捆绑包在浏览器中合并静态HTML标记。 它将其转变为可以对客户端数据更改做出React的动态DOM。
Nuxt does this all out of the box for us, so you don’t have to write this setup manually. Lots of complexity goes into the last two steps — packaging and bundling. But Nuxt hides all of it from you. You can concentrate on the application code that eventually delivers the final application.
Nuxt为我们提供了开箱即用的功能,因此您无需手动编写此设置。 最后两个步骤涉及很多复杂性-包装和捆绑。 但是Nuxt对您隐藏了所有这些内容。 您可以集中精力于最终交付最终应用程序的应用程序代码。
I hope this higher level overview of the application code structure takes you one step further in your learning journey of the Nuxt framework.
我希望对应用程序代码结构的更高层次的概述可以使您在学习Nuxt框架的过程中迈出新一步。
This is one of many alternate perspectives to help you make sense of how everything fits together in a Nuxt application.
这是许多替代观点之一,可以帮助您理解Nuxt应用程序中的所有内容如何组合在一起。
For me personally, this little exercise helps me:
对我个人而言,这种小运动可以帮助我:
Feel free to reach out with comments, feedback or even a suggestion for new diagram ideas you would like to see — in the comment section below.
欢迎在下面的评论部分中与您想看到的新图表想法相关的评论,反馈甚至建议。
If you’re new to Nuxt, then you may want to check out my earlier article on this topic “Why Nuxt Js is the perfect framework for your landing page? That will give you deeper insight in the nitty-gritty of developing applications with Nuxt.
如果您是Nuxt的新手,那么您可能想看看我以前关于此主题的文章“ 为什么Nuxt Js是您的目标网页的理想框架? 这将使您更深入地了解使用Nuxt开发应用程序的本质。
When @_achopin asked at the @vuejsamsterdam, “Are you Nuxt?” I thought, hey… I am Nuxt.
当@_achopin要求在@vuejsamsterdam ,“你Nuxt?” 我以为,嘿...我是Nuxt。
And I created these Nuxt stickers — professionally printed by Moo Printing and ready to be shipped if you’re interested. Alternatively, you can order them on RedBubble as well.
我创建了这些Nuxt贴纸 -由Moo Printing专业印刷,如果您有兴趣可以随时发货。 另外,您也可以在RedBubble上订购它们。
翻译自: https://www.freecodecamp.org/news/universal-application-code-structure-in-nuxt-js-4cd014cc0baa/
nuxt.js的核心代码