Home > Web Front-end > JS Tutorial > ThinkJS development config example tutorial

ThinkJS development config example tutorial

零下一度
Release: 2017-07-26 18:02:58
Original
2034 people have browsed it

Define configuration files by module

thinkjs allows developers to configure their own parameters directly under src/common/config/ and directly add js files. The file name only needs to comply with json The attribute name is required, and the file content follows the following format:

// 新增文件 assets.js 键入如下内容'use strict';export default {
  // key: value};
Copy after login

The file content only needs to conform to the definition of a json object format. Let’s look at a log4js configuration definition:

// log4js.js'use strict';export default {
  appenders: [{  type    : "console",  category: "console"},// 定义一个日志记录器{  type                : "dateFile",                 // 日志文件类型,可以使用日期作为文件名的占位符  filename            : "logs/",     // 日志文件名,可以设置相对路径或绝对路径  pattern             : "debug/yyyyMMddhh.txt",  // 占位符,紧跟在filename后面  absolute            : true,                   // filename是否绝对路径  alwaysIncludePattern: true,       // 文件名是否始终包含占位符  category            : "logInfo"               // 记录器名}
  ],
  levels   : {logInfo: "DEBUG"
  }        // 设置记录器的默认显示级别,低于这个级别的日志,不会输出}
Copy after login

Configuration files are static settings and generally store setting parameters that do not change frequently (of course, the values ​​of configuration parameters can be changed in memory, as detailed below illustrate).

In addition, the configuration file is a js file that exports variable definitions in ES6 format, not a json file. The advantage here is that you can add comments starting with //.

If you are careful, you must have discovered: In addition to src/common/config, there is also a config file under the src/home/ module folder.

Generally speaking, it is more reasonable to define and arrange according to the scope of the configuration file.

For example: configurations used by all modules are more appropriate to be placed under src/common/config, while configurations used only for the home module are placed under src/home/ config The following is more appropriate.

When there are too many configuration files, we need to pay attention to the loading order of multiple configuration files.

Configuration file loading sequence

The official website describes the configuration file loading sequence as follows:

Framework default configuration-> Framework configuration in project mode -> Project public configuration -> Public configuration in project mode -> Configuration under module

Let me ask a question first: Where do these five configurations refer to?

The first two can be ignored. They are the configuration settings of the thinkjs framework itself. Usually there are no configuration parameters that our project will use.

The third and fourth are the default config configuration folders under different project creation modes (for project creation modes, see Node.js Domestic MVC Framework ThinkJS Development Introduction (Jingxiu.com)), the location In:

# normal modethinkjs_normal/src/config/*# module modethinkjs_module/src/common/config/*
Copy after login

The last one refers to the project in module mode. Each module has its own config, located at:

thinkjs_module/src/home/config/*
Copy after login

It should be noted that multiple configuration files will eventually be loaded when thinkjs is running and merged together (note the bold text).

So when there are multiple configuration files, you need to pay attention to The key (i.e. attribute name) of the configuration parameter should not be repeated , because according to the loading order, the value of the key loaded later will overwrite the first one. The value of the loaded key leads to undesired results.

Tip: The tutorial mainly explains the development method in module mode.

Automatically switch configuration files

As mentioned earlier, we can place the configuration file under src/common/config. All configuration parameters can be placed in one file, or can be spread across multiple files.

There is a common scenario that I believe every developer will encounter:

Some configuration parameters are only used for local development, and some are only used for online operation. When the development was completed and continuous integration was being done, when the configuration parameters were uploaded, it was found that the development parameters and online parameters were mixed together. . .

thinkjs provides three configuration parameter environments under src/common/config/env/, namely development configurationdevelopment and production configurationproduction, test configurationtesting, can save our continuous integration.

We can divide the project configuration into three parameters with the same attribute name and place them in different configuration environments. In this way, thinkjs automatically loads the development configuration during local development, and the production configuration is loaded online after continuous integration. , is it very convenient~

Development configuration

The development configuration file is: src/common/config/env/development.js

As before As mentioned, the development configuration is suitable for local development, so how does thinkjs know which environment it is now?

The answer is: It has been defined in package.json

{
  "scripts": {"start": "node www/development.js?1.1.11","compile": "babel src/ --out-dir app/","watch-compile": "node -e \"console.log(&#39;<npm run watch-compile> no longer need, use <npm start> command direct.&#39;);console.log();\"","watch": "npm run watch-compile"
  }}
Copy after login

You can see that the scripts.start attribute is defined and we use it directly# When ##npm start is executed, the node www/development.js command is actually executed.

In line with the principle of breaking the casserole and asking the truth, take a look at what is in this file:

var thinkjs = require(&#39;thinkjs&#39;);var path = require(&#39;path&#39;);var rootPath = path.dirname(__dirname);var instance = new thinkjs({
  APP_PATH: rootPath + path.sep + &#39;app&#39;,
  RUNTIME_PATH: rootPath + path.sep + &#39;runtime&#39;,
  ROOT_PATH: rootPath,
  RESOURCE_PATH: __dirname,
  env: &#39;development&#39;  // <-- 这里定义了当前的 thinkjs 实例的运行环境});// Build code from src to app directory.instance.compile({
  log: true});instance.run();
Copy after login

:-)

生产配置

生产配置文件是:src/common/config/env/production.js

明白了开发配置的原理,也就不难明白生产配置了。

使用 node www/production.js 命令可以告诉 thinkjs 现在运行的是生产环境。

同理,生产配置中的参数名(属性名)一般与开发配置一样,只是值不同而已。

比较常见的是数据库连接,本地开发时连接的是测试库,而生产环境中连接的是生产库,不同的地址、用户、密码和库名,这些都是要交给运维人员来管理了。

测试配置

测试配置文件是:src/common/config/env/testing.js

明白了前两个配置,这个也不难明白~

使用 node www/testing.js 命令可以告诉 thinkjs 现在运行的是测试环境。

定义和使用配置文件

前面其实有介绍过配置文件的分布原则和定义方法,只要确保不与系统特定配置冲突即可自由定义。

系统特定配置

下面是 thinkjs 默认的配置文件清单,这些系统特定配置都是有相应的使用场景和参数设置,详细说明及完整参数详见:

src/common/config/├── config.js  # 可以放置自己的配置├── db.js  # 数据库连接├── env  # 运行时配置,下面会详述│   ├── development.js│   ├── production.js│   └── testing.js├── error.js  # 错误配置├── hook.js  # 钩子配置├── locale  # 多语言版配置│   └── en.js├── session.js└── view.js  # 视图文件配置
Copy after login

自定义配置

一般做法是使用带有层级的配置定义来组织配置参数(当然你一定要把全部参数都放在根下面也不是不可以),参见如下配置:

// development.js&#39;use strict&#39;;export default {
  site_name: "",
  site_title: "",
  site_keywords: "",
  site_description: "",
  db: {  // 这里的配置替代 db.jstype   : &#39;mysql&#39;,log_sql: true, //是否记录 sql 语句adapter: {  mysql: {host    : &#39;127.0.0.1&#39;,port    : &#39;3306&#39;,database: &#39;&#39;,user    : &#39;&#39;,password: &#39;&#39;,prefix  : &#39;thinkjs_&#39;,encoding: &#39;utf8&#39;  }}
  },
  jwt: { // 第三方模块的公共定义options: {  algorithm: &#39;HS128&#39;,  expiresIn: &#39;7d&#39;}
  },
  pay: {// 定义与在线支付接口相关的参数
  },
  backend: {// 定义管理后台相关的参数
  },
  home: {// 定义前端网站相关的参数
  },
  rest: {// 定义 REST API 相关的参数
  },
  task: {// 定义 crond 相关的参数
  }};
Copy after login

配置参数按照层次组织之后,需要注意的一点是:获取配置的时候,不能无限制的 this.config(参数.参数.参数.参数) 下去,详见下面读取配置的几种方式描述。

几种读取配置的方式

配置文件定义之后,需要在项目运行的特别业务中读取(也可以设置)到配置参数的值,根据读取配置的位置的不同,thinkjs 提供了以下几种读取方式。

this.config()

这是使用率最高的读取配置方法,绝大多数位置都可以使用此方法来读取配置,比如 controller logic model service middleware 等地方。

// 配置 development.jslet dbOpt = this.config(&#39;db&#39;);let jwtOpt = this.config(&#39;jwt.options&#39;);
Copy after login

这里有一点需要注意:thinkjs 只能解析两层配置参数,超过的层级不予解析(源码中写死了仅返回两层)。

// 配置 development.jslet jwtOpt = this.config(&#39;jwt.options&#39;);console.log(jwtOpt);// 读取成功,打印:// {//   options: {//     algorithm: &#39;HS128&#39;,//     expiresIn: &#39;7d&#39;//   }// }let jwtOptAlg = this.config(&#39;jwt.options.algorithm&#39;);console.log(jwtOptAlg);// 超过三层,读取失败,只能读取到两层内容,打印:// {//   options: {//     algorithm: &#39;HS128&#39;,//     expiresIn: &#39;7d&#39;//   }// }jwtOptAlg = jwtOpt[&#39;algorithm&#39;];console.log(jwtOptAlg);// 正确的读取方式,打印:// HS128
Copy after login

think.config()

think.config 方法可以:

  • 无须考虑当前位置来读取配置参数(其内部运行方式类似 this.config )

  • 跨模块读取配置参数

对于前者可以无须思考当前所在的模块,更自由的读取配置参数。

对于后者则对开发多模块协作有着比较重要的意义,配置参数只有一份,不可能向不同的模块复制相同的配置,因此需要“一处配置、多处可用”。因此无须考虑“我在哪里读取配置”,只要考虑“我要读取哪里的配置”即可。

// 配置文件:src/home/config/assets.jslet siteName = think.config(&#39;assets.site_name&#39;, undefined, &#39;home&#39;);
Copy after login

方法的第二个参数设置为 undefined 是为了避免将读取动作变为设置动作。

方法的第三个参数标明了这个配置参数在哪个模块下面,一旦给定此参数,thinkjs 会认为 src/home/config/ 下面的配置是你需要读取的目标。

http.config()

http.config 方法实质上是 think.config() 的一个别名,可以读取和设置配置参数。

避免踩坑之正确读取参数

如果不能理解 thinkjs 设计配置文件读取策略的情况下,会无意中踩坑,如下便是一个例子,代码说话。

假设有两个配置文件 src/common/config/assets.jssrc/home/config/assets.js,其中有着一样的属性名:

// src/common/config/assets.jsexport default {
  "site_title": "my site"};// src/home/config/assets.jsexport default {
  "site_title": "my test"};// 两个配置参数属性名一样的情况下// 使用不同的读取方式// 注意 config 方法的上下文对象的不同// 会导致读取的结果的不同// src/home/controller/index.jslet assets = this.config(&#39;assets&#39;);let siteTitle = assets[&#39;site_title&#39;];console.log(&#39;siteTitle is: &#39;, siteTitle);// 打印:// my test// src/home/controller/index.jslet assets = think.config(&#39;assets&#39;, undefined, &#39;common&#39;);let siteTitle = assets[&#39;site_title&#39;];console.log(&#39;siteTitle is: &#39;, siteTitle);// 打印:// my site
Copy after login

明白了 thinkjs 配置文件加载顺序,就不会对上面发生的情况惊讶了~

如果你实在懒得去思考 this.configthink.config 两者的分别,建议你干脆使用后者,当读取参数只传入第一个参数时,它的表现与前者一致。这样貌似更有利于代码的维护~

避免踩坑之动态修改配置参数

当读取到了配置参数后,当然是可以动态修改其为新的值,以让后续的处理都读到新的值。动态修改方法也很简单:config 方法的第二个参数就是给定的新值。

let siteTitle = this.config(&#39;assets.site_title&#39;);console.log(siteTitle);// 打印:// my testthis.config(&#39;assets.site_title&#39;, &#39;test 123&#39;);siteTitle = this.config(&#39;assets.site_title&#39;);console.log(siteTitle);// 打印:// test 123
Copy after login

上面的动态修改方法其实平淡无奇,来看看更有趣的修改方法,如下:

let siteAuthor = this.config(&#39;assets.site_author&#39;);console.log(siteAuthor);// 打印:// {//   name: &#39;xxuyou.com&#39;,//   email: &#39;cap@xxuyou.com&#39;// }siteAuthor[&#39;name&#39;] = &#39;cap&#39;;siteAuthor = this.config(&#39;assets.site_author&#39;);console.log(siteAuthor);// 打印:// {//   name: &#39;cap&#39;,//   email: &#39;cap@xxuyou.com&#39;// }
Copy after login

假如上面的代码片段修改一下写法,就可以得到预期的效果,如下:

let siteAuthor = think.extend({}, this.config(&#39;assets.site_author&#39;)); // <-- 不同点在这里console.log(siteAuthor);// 打印:// {//   name: &#39;xxuyou.com&#39;,//   email: &#39;cap@xxuyou.com&#39;// }siteAuthor[&#39;name&#39;] = &#39;cap&#39;;siteAuthor = this.config(&#39;assets.site_author&#39;);console.log(siteAuthor);// 打印:// {//   name: &#39;xxuyou.com&#39;,//   email: &#39;cap@xxuyou.com&#39;// }
Copy after login

Regardless of what this think.extend is, why does modifying the variable on the left side of the equal sign have the same effect as directly modifying the configuration method?

The reason is actually very simple:

  1. thinkjs caches configuration parameters internally.

  2. The value of the configuration parameter is an Object instead of a String.

OK~

Language package

The language package itself can actually be described separately as i18n, but due to internationalization in the actual development and even architecture process It is rarely covered, so it is briefly described here.

src/config/locale/en.js

The system's default English language environment, which defines related language templates.

src/config/locale/zh-CN.js

For the sake of standardization, it is recommended to manually set up this language template file and modify src/common/config/local.js## The default parameter in # is zh-CN to enable this language template.

The above is the detailed content of ThinkJS development config example tutorial. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template