The project I am currently in charge of is about to start reconstruction. Although I have written demo of Node and Webpack before, I still have not a comprehensive understanding of the overall framework. In the process of building this time, I have understood the role of each middleware. A lot of revenue. And some important knowledge points are summarized.
The overall train of thought
Multi-route multi-page application designCopy the code
The directory structure
. ├ ─ ─ client │ ├ ─ ─ libs │ │ └ ─ ─ qn. Js │ ├ ─ ─ NPM - scripts │ │ ├ ─ ─ _prompt. Js │ │ └ ─ ─ dev. Js │ ├ ─ ─ package. The json │ ├ ─ ─ pages │ │ └ ─ ─ 2019 - spokesman │ ├ ─ ─ webpack │ │ └ ─ ─ getPlugins. Js │ ├ ─ ─ webpack. Dev. Js │ └ ─ ─ webpack. Pro. Js ├ ─ ─ dist │ ├ ─ ─ Index. Js │ └ ─ ─ index. Js. Map ├ ─ ─ nodemon. Json ├ ─ ─ package. The json ├ ─ ─ public │ ├ ─ ─ dist │ │ ├ ─ ─ 2019 - spokesman - the main - 9 f9d20d4. Js │ │ ├ ─ ─ 2019 - spokesman - the main - 9 f9d20d4. Js. Map │ │ ├ ─ ─ 2019 - spokesman - vendor - 8702176 e. js │ │ └ ─ ─ 2019 - spokesman - vendor - 8702176 e. js. Map │ └ ─ ─ the favicon. Ico ├ ─ ─ server │ ├ ─ ─ the config │ │ ├ ─ ─ env │ │ ├ ─ ─ but ts │ │ └ ─ ─ qconf. Ts │ ├ ─ ─ but ts │ ├ ─ ─ middlewares │ │ ├ ─ ─ pageNotFound. Ts │ │ ├ ─ ─ registerRouter. Ts │ │ └ ─ ─ wechat. Ts │ ├ ─ ─ Routers │ │ └ ─ ─ demo. Ts │ ├ ─ ─ types │ │ ├ ─ ─ the config, which s │ │ └ ─ ─ wx. Which s │ └ ─ ─ wx │ ├ ─ ─ but ts │ └ ─ ─ libs ├ ─ ─ Json ├ ── 2019-888.hBSCopy the code
The entry file — index.ts under the server file
-
koa 2+
-
Koa-base-logger Logger middleware
-
Koa-body POST request middleware
- The POST request data is stored in ctx.request.body by default
app.use(koaBody({ // Whether multipart-formdate forms are supported. The default is false multipart: true,}))Copy the code
-
Koa-views processing template middleware
app.use(Views(viewsPath, { extension: 'hbs'.// Map the file extension to the engine map: { hbs: 'handlebars'}}))Copy the code
-
Koa-helmet HTTP request header, security related Settings
-
Koa -static file middleware
const serve = require('koa-static') app.use(serve(path.resolve(__dirname, 'xxx'))) // xxxwenji require('koa-static')(root, org) // 官方解释 : root directory string. Access the entire server directory based on the static resource file address and do the following. // For redirection requests based on method: get and protocol: HTTP, malicious bands are prohibited':'Access/link https://App.blued.cn:443/file%3a///etc/passwd/problemif (/\w*:/i.test(decodeURIComponent(ctx.path))) { ctx.redirect('/common/error/404') return false } Copy the code
-
Koa-router Specifies the routing middleware
-
koa-compose
-
Glob matches the file glob.sync(‘*.js’) returns an array of JS files in the current folder
-
Processing access address Status When ctx.status is 404,403, the page address is redirected
-
Other configurations of middleware
The front page
Webpack configuration
-
CSS is separated from JS
import ExtractTextPlugin from 'extract-text-webpack-plugin' Copy the code
- If your style file size is large, this will make preloading faster, because CSS bundles are loaded in parallel with JS bundles.
-
HappyPack
Webpack running on Node.js is a single-threaded model. Happypack splits tasks into sub-processes for concurrent execution, which then sends the results to the main process
- parameter
{threadPool: // Indicates a shared process pool. That is, multiple HappyPack instances use subprocesses in the same shared process pool to process verbose taskstrueThreads // indicates that several sub-processes are started to handle this type of file. The default is 3. The type must be integer. }Copy the code
- Each HappyPack instantiated with new HappyPack() tells the HappyPack core scheduler how to convert a class of files through a series of Loaders, and can specify how to assign subprocesses to such conversion operations.
-
Loaders loaders: [‘babel-loader? CacheDirectory ‘] You can also speed up the babel-loader at least twice by using cacheDirectory. This caches the results of the translation into the file system.
plugins
-
webpack.DefindPlugin
- Because this plug-in performs text substitution directly, the given value must contain the actual quotes inside the string itself. Generally, there are two ways to achieve this effect, using
"production"
, or usingJSON.stringify('production')
.
- Because this plug-in performs text substitution directly, the given value must contain the actual quotes inside the string itself. Generally, there are two ways to achieve this effect, using
-
Html-webpack-plugin dynamically injects CSS JS into HTML templates
-
hash chunkhash contenthash
- Chunkhash Specifies the hash value calculated based on the module content
- Contenthash represents the hash value of the text file content
Dynamically generate script commands
- Inquirer interactive command tool
inquirer.prompt(questions).then(({... }) => {}) The argument passed to the prompt method is an array of question questionsCopy the code
question = [ { typeName: String, // The key message for the current question in the answers object: String | Function, the problem of / / print title, if for Function default: String | Number | Array | Function, / / the user does not enter to answer it, the default value of the problem. Or you can use a functionreturnA default value. If is a function, the first argument of the function is the input answer to the current question. Choices: Array | Function, / / given a selection list, if is a Function, enter the answer to the question of the first parameter to the current. When is an array, each element of the array can be a value in the base type. Validate: Function, // accepts input from the user, and returns if the value is validtrue. When the function returnsfalseA default error message is provided to the user. Filter: Function, // takes user input and converts the value back to populate the last answers object. When: the Function | Boolean, / / accept the answers for the current user input object, and by returntrueorfalseTo determine whether the current question should be asked. It can also be a simple type of value. PageSize: Number, // Change the length of lines rendered to list, rawList,expand, or checkbox. }]Copy the code
- Ora corner mark
Distinction between require and import
The commonJs specification imports modules with the modules.exports interface to require
Modules.exports is a node private global variable property that has nothing to do with the standard
- Export Indicates the interface for exporting the module
// Error demonstrationexport1; Var a = 100;export a;
Copy the code
When exporting an interface, export must have a one-to-one relationship with variables in the module. It makes no sense to export 1 directly, and it is impossible to import a variable that corresponds to it. Export seems to be valid, but the value of a is a number, which cannot be deconstructed at all. Therefore, it must be written in the form of export {a}. Even if A is assigned as a function, it is not allowed. Furthermore, most styles suggest that modules export all interfaces with an export at the end. Such as:
export {fun as default, a, b, c}
Copy the code
- Import The import module import must be placed at the beginning of the file, and
No other logical code is allowed in front of it
The use of import, like export, is also quite complicated, which can be roughly understood here.
import $ from 'jquery';
import * as _ from '_';
import {a,b,c} from './a';
import {default as alias, a as a_a, b, c} from './a';
Copy the code
The basic usage is that import is followed by curly braces. The variables in curly braces correspond to the variables following export.Copy the code
-
The as keyword
var a = function() {}; export {a as fun}; // b.js import {fun as a} from './a'; a(); Copy the code
In the case of export, the interface provided externally is fun, which is the alias of the function A inside a. Js. However, outside the module, it is easy to recognize only as in fun import. When you use a method inside the module, give the method an individual name.
-
The syntax of the default keyword alias can be used to sugar import without curly braces. Simply put, if you find a variable that is not enclosed in curly braces (no asterisks) when importing, you should mentally revert it to the as syntax with curly braces.
import a,{each,map} from 'jquery' Copy the code
- The first a after import is
{default as a}
The syntactic sugar
- The first a after import is
-
* symbol
* stands for all and is used only in import,
import * as _ from '_' Copy the code
It is different from import _ from ‘_’ in that it means that all interfaces in the ‘_’ module are mounted to the _ object, so an interface can be called with _. Each
Alternatively, the interface of a module can be directly inherited by the * sign
export * from '_'Import * as all from'_' export all; Copy the code
Use the * symbol as sparingly as possible. It actually uses all of export’s interfaces, but it is likely that your current module will not use all of them, so the best advice is to use curly braces, one plus one
-
Should I use require or import
Module. Exports. What is the content behind module. Exports Module. Exports = require/module. Exports = module. I’m still not sure when to use “import” and when to use “require”