Hd web disk XZ:lexuecode.com/4477.html
Nuxt3 introduction
Nuxt3 has recently entered the beta phase, if you are interested, please check it out.
Nuxt3, as described on the official website, builds your next application with Vue 3 to experience hybrid rendering, powerful data capture, and new features. Nuxt 3 is an open source framework that makes Web development simple and powerful. Making the address
Nuxt 3 has been redesigned with a smaller kernel and optimized for faster performance and a better developer experience.
New features are as follows:
Equivalent to 75 times smaller server deployments, and smaller client packages; Nitro-based dynamic code separation and cold startup; In either component, data can be retrieved before and after rendering; Use Composition API and Nuxt 3’s composable components for true code reuse; Zero-dependent scaffolding for easy module integration; In the browser, it can process information quickly and fix it quickly. Faster build times, smaller package sizes, and no additional configuration required; Lightning-fast HMR when you use Vite; Vue3 is an important building block for your next application; Building with native TypeScript and ESM requires no additional steps.
Vue3+Nuxt3 build SSR website application, 0 to 1 to achieve server-side rendering – combat
Vue3 is already the default, so it’s time to get your hands on a working Vue3 project
Create a folder
mkdir vue3
Copy the code
Enter the folder to initialize the project, according to their own needs to set the relevant fields, do not need to fill all the way enter
cd vue3
npm init
Copy the code
Use Vite
1. Install vite
npm i vite -D
Copy the code
2. Run scripts with configuration
"Dev ": "vite" // Development environment "build": "vite build" // package environment "preview": "vite preview"// preview environmentCopy the code
3. Set the entry HTML file
<! DOCTYPE html> <html lang="zh-cmn-Hans"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial scale=1.0"> <title>VUE</title> <meta name="keywords" content=""> <meta name="description" content=""> </head> <body> <div id="app"></div> <script type="module" src="/src/main.ts"></script> </body> </html>Copy the code
4. Create the SRC file directory and create the main.ts file
console.log('main.ts');
Copy the code
5. Start the project
npm run dev
Copy the code
6. Open a browser and access port 3000
If you open the console and see the control output “main.ts”, it indicates that vite has started successfully
1. Create an empty vite configuration file, vite. Config. js
import { defineConfig } from 'vite'
// https://vitejs.dev/config/
export default defineConfig({})
Copy the code
2. Support VUE
1) Install vite plug-in package that supports VUE
npm i @vitejs/plugin-vue -D
Copy the code
2) Modify the vite. Config. js file
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()]
})
Copy the code
3) Create the app. vue file in the SRC directory
<template>
<a href="https://www.51cto.com">51CTO</a>
</template>
<style>
a{
color: red;
}
</style>
Copy the code
4) Modify main.ts
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
Copy the code
Quickly Build an SSR using Vite (Practical SSR)
Vite SSR, although now of an experimental nature, cannot be used in a production environment. But we can use Vite to do a SSR demo to help us understand SSR construction, after understanding we will introduce “Nuxt”, “isomorphism” and other concepts. Vite provides a lot of support for SSR, so we are going to develop a demo, it will be very, very simple, you can also refer to this official website document
We first need to change the contents of index.html
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" href="/favicon.ico" /> <meta name="viewport" content="width=device-width, Initial =1.0" /> <title>Vite App</title> </head> <body> <div id=" App "></div> <script type="module" SRC ="/ SRC /entry-client"></script> </body> </ HTML > You can see that we wrote a comment in the div of the app, and when we render the HTML will replace the comment. Then we need to create a new server.mjs in the root directory as our service entry, using Express as an example: import { readFileSync } from 'fs' import { resolve } from 'path' import express from 'express' import { createServer as createViteServer } from 'vite' const createServer = async () => { const app = express() const vite = await createViteServer({ server: { middlewareMode: 'ssr' } }) app.use(vite.middlewares) app.use('*', async (req, res) => { try { const url = req.originalUrl let template = readFileSync(resolve('index.html'), 'utf-8') template = await vite.transformIndexHtml(url, template) const { render } = await vite.ssrLoadModule('./src/entry-server.js') const appHtml = await render(url) const html = template.replace(`<! --ssr-outlet-->`, appHtml) res.status(200).set({ 'Content-Type': 'text/html' }).end(html) } catch (error) { vite.ssrFixStacktrace(e) console.error(e) res.status(500).end(e.message) } }) app.listen(3000) } createServer()Copy the code
Our main.js also needs to be changed
import App from './App.vue' import Router from './router' import { createSSRApp } from 'vue' export function createApp() { const app = createSSRApp(App) app.use(Router) return { app, router: Router}} In main.js, we export the createSSRApp function from vue, use Router, and return an object that will later be referenced by entry-server. The router is also different from our traditional CSR application. We passed in different routing types according to env: import { createRouter, createWebHistory, createMemoryHistory } from 'vue-router' const Router = createRouter({ history: import.meta.env.SSR ? createMemoryHistory() : createWebHistory(), routes: [ { name: 'index', path: '/index', component: () => import('../pages/index.vue') } ] }) export default RouterCopy the code
Then we need to create entry-client.js in SRC (which will be imported by index.html) and entry-server.js
import { createApp } from './main'
const { app, router } = createApp()
router.isReady().then(() => {
app.mount('#app')
})
import { createApp } from './main'
import { renderToString } from 'vue/server-renderer'
export const render = async (url) => {
try {
const { app, router } = createApp()
router.push(url)
await router.isReady()
const ctx = {}
const html = await renderToString(app, ctx)
return html
} catch (error) {
}
}
Copy the code
At this point we can start a server locally and render our pages in SSR format to the browser. Since our demo code is esM, we will execute using Node, which has to be written as an MJS suffix.
After starting the server, visit the /index route and you will see our page. Above is Vue3+Nuxt3 to build SSR website application, 0 to 1 to implement server side rendering