search
HomeWeb Front-endJS TutorialThinkJS development config example tutorial

ThinkJS development config example tutorial

Jul 26, 2017 pm 06:02 PM
javascriptnode.js

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};

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"
  }        // 设置记录器的默认显示级别,低于这个级别的日志,不会输出}

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/*

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

thinkjs_module/src/home/config/*

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"
  }}

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();

:-)

生产配置

生产配置文件是: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  # 视图文件配置

自定义配置

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

// 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 相关的参数
  }};

配置参数按照层次组织之后,需要注意的一点是:获取配置的时候,不能无限制的 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;);

这里有一点需要注意: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

think.config()

think.config 方法可以:

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

  • 跨模块读取配置参数

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

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

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

方法的第二个参数设置为 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

明白了 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

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

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;// }

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

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;// }

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!

Statement
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
Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.