nuxt.js的核心代碼
by Krutie Patel
通過克魯蒂·帕特爾(Krutie Patel)
Nuxt.js中的通用應用程序代碼結構 (Universal application code structure in Nuxt.js)
Nuxt.js中的源代碼結構的簡要摘要 (A brief summary of source code structure in Nuxt.js)
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開始。
Vuex商店(/商店) (Vuex Store (/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.
當用戶最初訪問您的應用程序時,這有助于填充/更新商店。 它還可以維護整個應用程序中數據的狀態。
路由中間件(/中間件) (Route Middleware (/middleware))
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:
從這里,您可以通過以下方式使用它們:
- Global middleware — (entry via Nuxt config and affects all routes) 全局中間件-(通過Nuxt配置進入并影響所有路由)
// nuxt.config.js
export default { router: { middleware: 'authenticated' },}
- Layout middleware (entry via layouts and affects group of matching routes, i.e. certain pages only to be viewed/accessed by authenticated users) 布局中間件(通過布局進入并影響一組匹配的路線,即某些頁面僅由經過身份驗證的用戶查看/訪問)
// layouts/default.vue
export default { middleware: 'authenticated-basic-plan-user'}
- Page middleware (entry via page component and affects single route) 頁面中間件(通過頁面組件進入并影響單個路由)
// 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.
上面的中間件是按照確切的順序處理的-這意味著它們的優先級是不可協商的。 因此,您必須仔細考慮并計劃應用程序,以充分利用它們。
Vue組件 (Vue Components)
There are three directories where .vue files are created in a Nuxt project.
在Nuxt項目中創建三個目錄的.vue文件。
1.頁面組件 (/頁) (1. Page components ? (/pages))
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 }
}
2.布局組件(/布局) (2. Layout components (/layouts))
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.
將路由中間件與布局組件相結合,并存儲數據狀態 ,以針對各種場景下的任意數量的用戶類型構建完善的“ 看誰看”功能。 您不僅可以通過自定義用戶界面實現更多目標。
3. Vue.js組件(/ components) (3. Vue.js components (/components))
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)
Webpacked資產(/資產) (Webpacked assets (/assets))
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)附加到已處理的項目,這有助于長期緩存動態資產和清除緩存。
靜態資產(/靜態) (Static assets (/static))
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會忽略靜態文件夾,并且不會在其中處理任何內容。
模塊,服務器中間件和插件 (Modules, serverMiddleware and plugins)
They are all defined (by their path) in Nuxt configuration. They are accessible globally within the Nuxt application.
它們都是在Nuxt配置中定義的(通過它們的路徑)。 在Nuxt應用程序中可以全局訪問它們。
模塊(/模塊) (Modules (/modules))
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(即/ api) (serverMiddleware (i.e. /api))
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來:
- Create an API endpoint to connect to external applications. 創建一個API端點以連接到外部應用程序。
- Create an API endpoint to send email to users from your Nuxt application. 創建一個API端點,以從您的Nuxt應用程序向用戶發送電子郵件。
- Access and modify the request in any way, even before it reaches Nuxt. 甚至可以在到達Nuxt之前以任何方式訪問和修改請求。
Note that you don’t have any pre-populated empty folders for serverMiddleware and modules. You create them when needed.
請注意,對于serverMiddleware和模塊,您沒有任何預填充的空文件夾。 您可以在需要時創建它們。
插件(/插件) (Plugins (/plugins))
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)組件中使用它們的方式。
模塊,服務器中間件和插件的高級概述 (High-level overview of modules, serverMiddleware and plugins)
包裝,捆綁和交付 (Package, bundle and deliver)
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實例。 如果您仔細查看.nu??xt / 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對您隱藏了所有這些內容。 您可以集中精力于最終交付最終應用程序的應用程序代碼。
結論 (Conclusion)
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:
對我個人而言,這種小運動可以幫助我:
- map out the requirements of the project against out-of-the-box Nuxt features 根據開箱即用的Nuxt功能繪制項目需求
- list relevant community modules & plugins that are already available, and 列出已經可用的相關社區模塊和插件,以及
- pick out the remaining/complex bits that require custom development. 選擇需要定制開發的其余/復雜位。
圖表鏈接與上面使用的圖表的高分辨率版本 (Diagrams links with high-res versions of the diagrams used above)
Nuxt Js lifecycle hooks
Nuxt Js生命周期掛鉤
Understanding modules, serverMiddleware and plugins
了解模塊,服務器中間件和插件
Universal application code in Nuxt.js
Nuxt.js中的通用應用程序代碼
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開發應用程序的本質。
你是納克斯嗎? (Are you Nuxt yet?)
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的核心代碼