1. Best Companies rank: 1
- Recently our official website reconstruction, an official website with a background, the purpose is dynamic configuration of the official website content, before are database write dead, in order to better operation of the website, reflect the brand influence, so there is a big change.
2. Requirements analysis
The demand is not complex, basically is several big module dynamic setting, production film introduction, news, position and so on. Since it is the official website of the enterprise, we should consider several issues:
- SEO
- The interface responds quickly, bringing better user experience
As we all know, the two fatal disadvantages of single-page apps are that SEO is not friendly, and the other is that the screen is blank for a long time. The so-called SEO is search citation optimization. To put it simply, the DOM structure of single-page applications is dynamically generated by JS, while crawlers prefer static pages, so single-page applications are not conducive to SEO. The main reason for the white screen loading is that it takes time to load components in a single page application, which leads to an unfriendly user experience. These two points are not obvious in the background management, but in the enterprise official website or blog and other websites, we need to find a way to solve.
The most common way to solve the above two problems is to use server-side rendering, the so-called server-side rendering is the server directly return to the HTML structure, a long time ago, before and after the end is not separated, JSP rendering way belongs to the server-side rendering. React Vue also has a response API to support server rendering. However, it is more difficult to do this by yourself. We can use the mature server rendering framework, next.js.
3. Next. Use js
Erection of scaffolding
npm install -g create-next-app
Copy the code
Generating project
create-next-app myWebsite
Copy the code
After the installation is successful, the corresponding prompt will be displayed:
cd myWebsite
yarn dev
Copy the code
When the browser opens localhost:3000 and the following page appears, a project is successfully started
The following is the project structure diagram after the scaffolding is generated:
Our main page will be created under Pages. Each page is a route, with index.js as the main entry. If we create a product folder under Pages and create an index.js file under product folder, Type localhost:3000/product in your browser to get to the Product page.
4. Specific configurations
-
Component development is definitely involved in your project, so create a components file in the root directory, and put all components in this folder. Note: according to the rules of next.js, requests cannot be sent from within a component; all requests need to be placed on the main page.
-
Where do I put the static files? Such as images, CSS files and so on. Also create a static folder in the root directory. You can create images or CSS files in the static folder
-
The UI framework of the project is ANTD, and ANTD is installed using NPM Install ANTd or YARN Add ANTd. After the installation is complete, you need to configure antD to load on demand. At this point, you need to create a.babelrc file in the root directory. In this file, add the following code:
{
"presets": ["next/babel"]. "plugins": [
[
"import". { "libraryName": "antd". "style": "less" } ]. [ "@babel/plugin-proposal-decorators". { "legacy": true } ] ] } Copy the code
- We want to use LESS files as well as CSS in our project. how can we do that? Create the next.config.js file in the root directory and add the following code to this file:
const withCss = require("@zeit/next-css");
const widthLess = require('@zeit/next-less');
if(typeof require ! = ='undefined') {
require.extensions['.css'] = file => { }
}
module.exports = widthLess(withCss({ lessLoaderOptions: { javascriptEnabled: true. importLoaders: 1, localIdentName: "[local]___[hash:base64:5]". }, distDir: 'build'. webpack: (config, { dev }) => { config.module.rules.push( { test: /\.(png|jpg|svg|eot|otf|ttf|woff|gif|woff2)$/, use: { loader: "url-loader? limit=8024". options: { name: "[name].[ext]" } } }, { test: [/\.eot$/, /\.ttf$/, /\.svg$/, /\.woff$/, /\.woff2$/], loader: require.resolve('file-loader'), options: { name: '/static/media/[name].[hash:8].[ext]' } } ) // config.plugins.push(new CleanWebpackPlugin()) return config } })) Copy the code
You can see that we used the @zeit/ Next-CSS and @zeit/ Next-less modules, both of which are used in Next-.js to support the use of style files. NPM Install installs them before using them. In the next.config.js file, you can customize the Webpack configuration. As you can see here, lessLoaderOption is configured to dynamically set the ANTD theme color, distDir is configured to declare the location of the packaged file, and some images, SVG, and other load configurations. The WENpack Loader must be installed before use. So you can use still images and other files in your project.
So far you can use ANTD normally, but what if you want to customize antD theme colors? The root directory creates the implies folder, and in that folder create antD-customs. Less and styles.les files, add the following CSS styles, respectively
@primary-color: #29CCB1;
@layout-header-height: 40px;
@border-radius-base: 4px;
Copy the code
@import "~antd/dist/antd.less";
@import "./antd-custom.less";
Copy the code
Then create the _app.js file under Pages and add the following code to the file
import App from 'next/app'
import '.. /asserts/styles.less'
export default App
Copy the code
Ok, your custom ANTD theme is now available.
When you need to configure cross-domains in a project, how do you do it? Next. Js supports custom servers. Also in the root directory, create a new server.js and add the following code:
// server.js
const express = require('express')
const next = require('next')
const { createProxyMiddleware } = require('http-proxy-middleware')
const devProxy = { '/api/v': { target: 'http://192.168.3.18:8092'// The port itself is configured appropriately // pathRewrite: { // '^/api': '/' // }, changeOrigin: true } } const port = parseInt(process.env.PORT, 10) || 80 const dev = process.env.NODE_ENV ! = ='production' const app = next({ dev }) const handle = app.getRequestHandler() app.prepare() .then(() = > { const server = express() if (dev && devProxy) { Object.keys(devProxy).forEach(function(context) { server.use(createProxyMiddleware (context, devProxy[context])) }) } server.all(The '*', (req, res) => { handle(req, res) }) server.listen(port, err => { if (err) { throw err } console.log(`> Ready on http://localhost:${port}`) }) }) .catch(err => { console.log('An error occurred, unable to start the server') console.log(err) }) Copy the code
Then configure it in the package.json file:
"scripts": {
"dev": "node server.js". "build": "next build". "start": "cross-env NODE_ENV=production node server.js"
},
Copy the code
This whole process, you can be happy business development. Take a look at the complete project structure:
Other next corresponding knowledge, you can go to the website https://nextjs.frontendx.cn/docs to check the specific knowledge.
Note: If you are missing a module during the above process, you can directly install NPM first.
5. Conclusion
Leave a comment if you have deployment or other development questions. For those of you who have never used next. Js, this document will help you get started quickly
This article is formatted using MDNICE