Nuxt.js--"Unlock the potential of Nuxt projects: start from configuration and move towards success

        The blogger opened a Nuxt.js column today, taking you to explore the essence of Nuxt.js and learn how to use its powerful functions to build excellent front-end applications. We'll discuss its core features, flexible routing system, optimization tips, and solutions to common problems. Whether you want to learn the basics of Nuxt.js, or want to master advanced techniques, this column will meet your needs. Next, let us embark on the journey of Nuxt.js and start an exciting journey of front-end development!

Pre-knowledge required :

Search Engine Optimization (SEO) : The process of optimizing your website and content to improve your ranking and visibility in search engines. It is a strategy and technique that helps a website get more organic (non-paid) traffic. But the application system developed with vue.js is not friendly to SEO.

Client-Side Rendering (CSR) : Client-side rendering is a style of web application rendering in which the content and structure of a page is generated and rendered primarily by the client browser at runtime rather than on the server side. In client-side rendering, the server is primarily responsible for serving data and basic HTML, CSS, and JavaScript files, which are then sent to the client browser. After the browser receives these files, it parses the HTML and CSS, and executes JavaScript code to generate dynamic content and interactions.

Server Rendering (SSR) : Server rendering is a way of rendering web applications in which the content and structure of the page is primarily generated on the server side and then sent to the client browser for display. In server rendering, after receiving the client's request, the server will generate corresponding HTML, CSS and JavaScript files according to the requested URL and parameters, and return these files to the client browser as a response. After the browser receives the file, it directly displays the content without performing additional operations.

The difference between client-side rendering and server-side rendering : When choosing server-side rendering or client-side rendering, you need to comprehensively consider factors such as project requirements, technical complexity, and performance requirements. Generally speaking, server-side rendering may be more suitable for websites that require fast loading and high SEO requirements; while for applications that require complex interactions and real-time updates, client-side rendering may be more advantageous.

How Vue.js implements SSR : Nuxt, a common application framework for vue.js, provides a smooth out-of-the-box experience, built on the same vue.js technology stack, but abstracts a lot of templates and provides some additional features, such as static site generation. Through NUXT, Vue SSR can be quickly implemented according to the agreed rules.

Table of contents

Basic explanation of nuxt basic configuration

Nuxt.config.js file configuration explanation

Add element-ui framework        

Local head configuration

nuxt configuration modules


Basic explanation of nuxt basic configuration

Configure the host and port number : If you want to change the host and port number in the nuxt project, it is very simple, just add a new config node in the package.json file. In order to facilitate the distinction, I set the host and port number casually (you need to modify the configuration file restart project):

"config": {
  "nuxt": {
    "host": "127.0.0.2",
    "port": "1818"
  }
},

The terminal executes npm run dev to run the project, and the results are as follows. It can be seen that the host and port number we configured have taken effect:

Of course, you can also use another way to add a server option in the nuxt.config.js file. This option is used to configure the connection server connection variable of the nuxt application. The default server connection is as follows:

If you want to run the project to automatically open the browser, just add -- open after the dev command to run the project to automatically open the browser

Aliases : In nuxt, ~ or @ aliases are used to associate srcDri attributes, and ~~ or @@ aliases are used to associate rootDir attributes. For example, if you intend to link images to the /static/ directory, you can use ~ aliases.

<template>
  <img src="~/static/img1.jpg" />
</template>

Nuxt.config.js file configuration explanation

When we use the nuxt build tool, we will get the nuxt.config.js file by default. This file is a global file that sets the entire project. When you open the file, you should see the following options (or properties):

export default {
  mode: 'universal',
  target: 'server', 
  head: {...},
  css: [],
  plugins: [],
  components: true,
  buildModules: [],
  modules: [],
  build: {},
  // 未出现的重要选项,根据项目需要自己添加配置
  env: {},
  loading: {},
  pageTransition: {},
  layoutTransition: {},
}

In the current project, except for mode, target (these two are deleted now), head, and components, most of the other contents are empty. We can use these custom nuxt to meet certain specific projects. Next, we will discuss these The options and how they are applied are explained separately:

mode option : It is used to define the "essence" of the application, that is, universal application or SPA. The default value of this option is universal. When using nuxt to develop SPA, just modify the value of this option to spa. This option is now removed, and the general pattern will be discussed in a later article.

target option : It is used to set the deployment target of the application, that is, deploy as a server-side rendering application or a statically generated application. For server-side rendering deployment, the default value of target is server. Now this option is deleted and will be explained later.

head option : used to define all default meta tags in the <head> block of the application, we can make multiple custom configurations, such as adding JavaScript and CSS libraries required by the project:

export default {
  head: {
    title: 'npx_nuxt',
    htmlAttrs: {...},
    meta: [
        //...
    ],
    script: [
      { src: 'https://cdnjs.lounflare.com../../jquery.min.js' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
      { rel: 'stylesheet', href: 'https://cdn/.../foundation.min.css' }
    ]
  }
}

css option : used to add global css files, these files can be .css, .less or .scss files, or modules and libraries loaded directly from the project's node.js/node_modules/ directory, as follows:

css: [
  'jquery-/jquery-ul-min.css',
  '@/sataic/less/styles.less',
  '~static/css/normalze.css',
],

plugins option : used to add JavaScript plugins, these plugins are run before the Vue root instance, the inspection code is as follows:

export default {
    plugins: ['~/plugins/vue-notifications']
}

Components option : It is used to set whether the components in the /components directory should be imported automatically. If the components option is set to true, then we do not need to import components manually. This is very user-friendly, and there is no need to set false.

buildModules option : Used to register built modules that are only used during the development and build phase of the application.

modules option : used to add nuxt modules to the project, examine the following code:

export default {
    modules:[
        '@nuxtjs/axios',
        '~/modules/example.js'
    ]
}

In addition, we can also use the modules option to directly create inline modules, as follows:

export default {
    modules:[
        function () {
            //...
        }
    ]
}

Build option : used to customize the webpack configuration. For example, if we want to install jQuery globally in the project without using the import statement, jQuery can be automatically loaded through the ProvidePlugin() function of webpack.

import webpack from 'webpack'
export default {
    build:{
        plugins:[
            new webpack.ProvidePlugin({
                $: "jquery"
            })
        ]
    }
}

env option : It is used to set the environment variables of the nuxt application client and server. The default value is not an empty object. When using axios in the project, the env option will be very useful. The investigation cases are as follows:

// nuxt.config.js
export default {
    env: {
        baseUrl: process.env.BASE_URL || 'http://localhost:3000'
    }
}

Then we can use the env property in the axios plugin, as follows:

// plugins/axios.js
import axios from 'axios'

export default axios.create({
    baseUrl: process.env.baseUrl
})

loading option : used to customize the loading component of the nuxt application, if you do not intend to use the default loading component, you can set the loading option to false:

// nuxt.config.js
export default {
    loading: false
}

pageTransition and layoutTransition options : default properties for customizing page and layout transitions in nuxt applications

// nuxt.config.js
export default {
    pageTransition: {
        name: 'fade'
    }
    layoutTransition: {
        name: 'fade-layout'
    }
}

Add element-ui framework        

When creating a nuxt project outside, there is a step for us to choose whether to download the UI component library. At that time, I chose none. Now when we want to use the ui component library, we need to download it ourselves:

Let’s take element as an example. First of all, we need to know what are Element UI and Element Plus? Element UI is an interface framework based on Vue2.x; Element Plus is an interface framework based on Vue3.x, because here we are using the nuxt2 version, which is also adapted to vue2, so we need to download element-ui This component library, let’s start directly without further ado:

Execute the following command on the terminal to install the element-ui component library:

npm i element-ui -S

After the installation is complete, create a plugins folder directly in the root directory, which is used to contain JavaScript functions, such as global functions that need to be run before instantiating the Vue root instance, so we create the element-ui.js file in this file, It is used to store the relevant configuration of the element-ui component library, as follows:

Add the following information to the element-ui.js file we created:

import Vue from 'vue'
import Element from 'element-ui'
// import locale from 'element-ui/lib/locale/lang/en'
import locale from 'element-ui/lib/locale/lang/zh-CN' // 引入中文插件
 
Vue.use(Element, { locale })
// Vue.use(Element)

Next, we need to configure the following information in nuxt.config.js:

After configuring nuxt.config.js, you need to re-run the project, and then write element-ui syntax in pages to check:

Local head configuration

When explaining the relevant configuration in the nuxt.config.js file, I have indicated that this file is a globally effective file. Friends who know nuxt know that the main purpose of this framework is to improve SEO, so in some cases we It is necessary to set the corresponding head for some local components, as follows:

<template>
  <div>
    关于我们
  </div>
</template>

<script>
export default {
  // 设置 head 相应局部配置
  head() {
    return {
      title: '关于我们',
      meta: [
        { hid: 'description', name: 'description', content: '关于此页面的描述' },
        { hid: 'keywords', name: 'keywords', content: '关于此页面的关键字' },
      ]
    }
  }
}
</script>

After the setting is complete, we can set the corresponding head of a separate partial component page:

Viewing the source code of the web page can also see some content and keywords we set, so that it can be crawled by crawlers:

Of course, the content of this head can also be dynamically displayed , similar to the news list, click on different news on the current page, the title and description under the head will change accordingly, so I won’t go into details here, just a brief mention.

nuxt configuration modules

The modules module in nuxt.config.js explained above is just a brief introduction. Next, we will introduce the use of this configuration item in detail. Take our commonly used axios as an example. When we install axios normally, the command is as follows , although this method can realize axios, on the premise of not encapsulating axios twice, if each component wants to use axios, it needs to be referenced separately:

npm i axios -S

Another command to install axios all the time is provided in the nuxt framework. Even if you don't package axios twice, you don't need to import axios in each individual component, just use it directly.

npm i @nuxtjs/axios -S

Since we all use the nuxt framework, we must choose the method recommended by nuxt. The second method requires the following configuration:

// nuxt.config.js
modules: [
    '@nuxtjs/axios',
]

Of course, if you want to configure the proxy, you need to follow the following command:

npm i @nuxtjs/proxy -S

This article mainly introduces the basic configuration of the Nuxt.js project. The next article will continue to explain the relevant knowledge of Nuxt.js. Follow the bloggers to not get lost and learn more front-end knowledge!

Guess you like

Origin blog.csdn.net/qq_53123067/article/details/132240381