JS & Nginx uses a simple case to explain the function and use of nginx ssi and seajs

Background & Preparations

1. Background

Recently, I received a request to transform an old project with some new functions. According to past experience, I think this request should be relatively simple and will not take long, so the delivery time for this request is relatively random.

In fact, when I came into contact with this project, I could vaguely feel the historical culture and style of code writing by the predecessors, and I also saw some strange syntax, which is not like the one that comes with js, and some of the code is not written like it is now. Specifications, this is understandable, after all, these concepts were not popular at that time.

Not much nonsense, the technology encountered in this article is what is written in the title. If you happen to be exposed to projects similar to this technology, and you are not very clear about what these technologies are used for, you might as well read on. If you just saw the title coming in, just understand; after all, compared to the current front-end development, these technologies are considered outdated.

2. Preparations

  1. Create a new project, eg nsg-example.

  2. The structure is as follows:
    Please add a picture description
    the app.js file here will be used later, so it should be created in advance.

  3. index.shtmlThe content is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div class="container">
    <h2>Hello,world!</h2>
  </div>
</body>
</html>

Because you want to use ssi, you have to use the .shtmlsuffix format to create a new file, and the rest is no different from ordinary html.

  1. Open it locally index.shtml, as shown in the figure:
    Please add a picture description

一、nginx ssi

1. nginx preparation

Before using the ssi function, we have to install nginx.
Download address: https://nginx.org/en/download.html
Select the stable version:
Please add a picture description
After downloading, extract it to the directory you want to store. The structure is as follows:
Please add a picture description

2. Use nginx to start the web server for the project

There is one in the directory where nginx is installed nginx.exe. After double-clicking, you will see a small black window flashing past. This is normal. Now visit: , as shown 127.0.0.1in the figure: Please add a picture description
It means that our web server has started.
Next, we need to implement access http://nsg.example.com/index.shtmlto map to the local project's index.shtml file.

Here are a few steps:

  1. Find nginx.confthe file
    Please add a picture description
  2. serverReplace the contents of the code block with:
server {
		 # 监听端口
        listen       80;
        # 设置域名,由于是本地环境,这里还要设置 hosts 文件,线上则不用考虑这个问题 。
        server_name  nsg.example.com;
        # 设置访问根目录,换成你的项目路径即可。
        root   D:\\Work\\Projects\\nsg-example; 
        location / {
        	# 访问 root 目录下对应目录。
            try_files $uri $uri/ =404; 
        }

        location = /50x.html {
            root   html;
        }
    }

Note: For the root path problem, in windows, one or two underscores can be used, for example D:\Work\Projects, but if there is a -separator , \\two underscores must be used, otherwise nginx will only resolve to D:Work\Projectsthis level, so It will not match our project directory. If you don’t believe it, you can try it yourself. The case project name here has separators. The correct way to write the path is: D:\\Work\\Projects\\nsg-example.

If you are not familiar with nginx configuration, you may wish to refer to what I wrote earlier: Nginx & detailed examples location -> index, return, rewrite, try_files, alias The meaning and precautions of each attribute

  1. Configure hoststhe file to support the server_name domain name in Nginx. The path is usually placed C:\Windows\System32\drivers\etc\hosts. Open the hosts file and add the following line:
127.0.0.1 nsg.example.com
  1. Open cmd as an administrator and execute the following command to refresh the DNS cache.
ipconfig /flushdns
  1. Execute the following command in the nginx directory to reload the configuration and start nginx.
nginx -s reload
  1. Now, let's visit http://nsg.example.com/index.shtmlas shown in the figure :
    Please add a picture description

3. what ssi

ssiIt is a response provided by Nginx to convert the ssi command into the specified content. Specifically, we can use the commands provided by ssi to achieve the desired rendering results. For example, we can introduce other html files in html, and dynamically display different content through the conditional statement commands provided by ssi. It is similar to the "template engine", but I think it is more of a dynamic import file + conditional command and exist.

4. Use ssi

First, enable the function nginx.confunder ssi:

location / {
     ssi on; # 开启 ssi
     try_files $uri $uri/ =404;
 }

After configuration, reload the configuration in the nginx directory:

nginx -s reload

ssiMany commands are provided, and interested students can refer to the documentation.
Here we cite some common ones, such as the include command to import files.
First, we can create a new one header.shtmlwith the following content:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <h1>Hello, Header!</h1>
</body>
</html>

Introduced in the original index.shtmlvia ssi directive:

<body>
  <!--# include virtual="/header.shtml" -->
  <div class="container">
    <h2>Hello,world!</h2>
  </div>
</body>

Explanation: !--# ... -->As ssithe only virtualidentification symbol, the inside is one of the parameters provided by include, which means to introduce a built-in request. In addition to .shtml, this request also supports request formats such as xxx.php xxx.jsp, provided that you have to configure proxy forwarding through nginx Hand it over to the FastCGI/uwsgi/SCGI/gRPC gateway.

Now revisit: http://nsg.example.com/index.shtmlYou can see that the instruction is parsed and executed:
Please add a picture description

Two, seajs framework

1. What is seajs

seajsIt exists independently of ssithe two and is not related in any way.

Background: For example, if you utils.jsdefine , and now other colleagues want to modify some functions in getName, but in order to avoid destroying the generality of getName and renaming, you have to create an alias based on getName such as getUserName, which will lead to When the project grows larger, it will cause problems for developers' readability and maintainability.

seajsIt is to solve the above original function naming conflicts and specification problems.

Its principle is very simple. It realizes modular syntax by simulating Node.js CMD. The core point is to 每个模块provide two parameters: exports / require is responsible for exporting and importing.

2. Use seajs

On index.shtmlthe basis , it is introduced through cnd seajs, as follows:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <!--# include virtual="/header.shtml" -->
  <div class="container">
    <h2>Hello,world!</h2>
  </div>
  <!-- 引入 seajs  -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/seajs/2.1.1/sea.js"></script>
  <script>
    // seajs 的简单配置
    seajs.config({
      
      
      base: "./src/modules", // 告诉 seajs 模块存放路径,后续 require 引入时节省前缀。
    });
    // 加载模块
    seajs.use("./src/app.js", function(module) {
      
      
      module.app.date.getCurrentTime()
    });
    
  </script>
</body>
</html>

As shown in the code, first use seajs.config to initialize the configuration, and then use seajs.use to import the app.js module. How does this module.app.date.getCurrentTimefunction come from? Don't worry, let's go step by step:

The first app.jsis a module, which introduces two other modules, the code is as follows:

define(function (require, exports) {
    
    
  // 直接引入模块因为前面在 seajs 已通过 config 配置好模块路径了。
  var date = require('date.js');
  var user = require('user.js');
  exports.app = {
    
    
    date: date,
    user: user,
  };
});

Explanation: It can be seen from the code that it is used define. It is a global function provided by seajs. The first parameter of this function is a callback function, which provides two core require/exportsparameter . The date.js & user.js modules are requireintroduced , and then exportsthese two modules are included and exported as an app object through .

Now we add a new modulesdirectory (configured by seajs.config), which defines the two module codes introduced by the app, as follows:

// date.js
define(function (require, exports) {
    
    
  exports.getCurrentTime = function() {
    
    
    return alert(Date.now());
  }
});
// user.js
define(function (require, exports) {
    
    
  exports.getUserNameById = function(id) {
    
    
    if (id === 10000) {
    
    
      return 'Jack';
    }
    return 'Guest'
  }
});

Now let's see the effect:
Please add a picture description

3. Common APIs

In fact, we have already used these APIs above, and there are not many common APIs, so here is a summary:

  • define
    • require introduces other defines
    • require.async introduces define asynchronously
    • exports Export objects, methods, etc.
  • seajs.useuse define
  • seajs.configInitialize seajs

4. Summary

  1. seajs solves the namespace problem
  2. seajs uses the require & exports provided by the define function to define modules and import other modules
  3. seajs imports the modules defined by define through use.

Guess you like

Origin blog.csdn.net/cookcyq__/article/details/129783405
Recommended