T1: Front-end engineering overview, Node.js foundation
Front-end engineering #2
Front-end engineering development tool set, easy to code compression, feature compatibility, the same format, precompiled files and other problems.
- Scaffolding tool
- Dedicated: vue-cli, create-reacet-app, Angular-cli, Gatsby -cli
- Common: Yeoman, Plop
- Automated builds: NPM scripts & Script hooks, Grunt, Gulp, FIS
- Modular packaging: Webpack, Rollup, and Parcel
- Standard specifications: ESLint, StyleLint, Prettier
- Automated tests: Mocha, Jest, Enzyme, Cypress, Nightmare, Puppeteer
- Automated deployment: Git Hook, Lint-staged, CI/CD
Node. Js
Node.js is a V8 engine based JavaScript runtime.
Like a browser, Node.js provides a runtime environment for JavaScript, built on top of Node.js
Node.js APIs #5
JavaScript in the browser includes ECAMScript and Web APIs, which include DOM and BOM;
JavaScript under Node.js includes ECMAScript and Node APIs, which include FS, PATH, OS, HTTP, etc
Node.js runs #7
Run on the command line
-
Script mode
In the file directory, enter node and the file name to execute the JS file.
-
Interactive mode
Type node and press Enter
In this mode, similar to browser Console, you can directly enter code to execute
Enter.exit to exit
Global object #8
The global object for JavaScript in the browser is window, and for Node.js is global
In interactive mode, declared variables and functions belong to global; In script mode, declared variables and functions are not part of global
Global function #9
Global functions include methods provided by JavaScript itself and methods under the global object global.
Global contains setTimeout, clearTimeout, setInterval, and clearInterval, which are the same as Windows on the browser. There are also new additions:
-
SetImmediate immediately executes the timer
Inserts to the top of the event queue
Differences with Process.net xTick:
The process.nextTick function is executed at the end of the main program, before the event queue.
-
ClearImmediate Clears the timer immediately
Node.js built-in module
Node.js has built-in modules, custom modules, and third-party modules.
The built-in module is the Node.js APIs, which can be used by installing Node.js. Install third-party modules by yourself before using them.
console #11
process #12~13
Process is a variable of global, so it is global. Introduction using require() is not required.
-
Arch current operating system architecture
-
Platform Indicates the current system platform information
-
CWD () Directory where the current file resides, CWD
The same value that __dirname points to
__filename is the full path to the current file, including the filename
-
Env environment variable
Custom environment variables can be newly defined under env
-
Pid Process ID
-
Kill (pid) Ends the process
path #14
Path must be introduced by require(). const path = require(‘path’);
Gets the directory where the current file resides
-
Extname (URL) Path to the file extension
-
The dirName (URL) path points to the directory part of the file
-
Basename (URL) The name of the file to which the path points (including the extension)
-
Join () joins paths and automatically completes /
Let fa = path.join(__dirname,’.. ‘);
Let another = path.join(__dirname,’another.js’);
fs #15~17
File System can realize File operation and management.
Operations on files
-
Empty write fs.writefile (fileName, content, callback)
Parameters:
- fileName
- Content: indicates the content of the file
- Callback: callback to be called after the write is complete
- Err: error
e.g. fs.writeFile(__dirname+’/1.txt’, ‘Hello,node.js! ‘, (err)=>{if (err) throw err; })
-
Read the fs. ReadFile (url, callback);
Parameters:
-
url
-
callback
-
err
-
Data: Binary data of the read file. The output is in hexadecimal by default.
Call toString to convert to a string
-
-
-
Delete the fs. Unlink (url, callback);
-
AppendFile (URL, content, callback);
Directory operations
-
Create directory fs.mkdir(url, callback)
-
Delete directory fs.rmdir(url, callback);
Only empty directories can be deleted
-
Rename the directory fs.rename();
-
Fs.readdir ()
Viewing File Information
- fs.stat()
- isDirectory()
- isFile()
Synchronous and asynchronous in FS
In addition to the methods described above, there are other methods with the suffix Sync to indicate synchronous execution
In general, asynchrony is used. Commands that emphasize sequencing use synchronous methods, such as
Copy and compress files #18
File stream # 19
The read stream flows through the pipe to the write stream
-
Create a read stream createReadStream()
Instances can be created by calling pipe() to the write stream as arguments.
-
Create a write stream createWriteStream()
HTTP #20
HTTP can publish Web services.
You need to introduce require before using it.
-
Create a service http.createserver(func)
Argument: a function
-
Req: request Request
- setHeader
- end
-
Res: Response Response
-
-
Publish service server.listen()
Custom modules
Each individual.js file in Node.js is a module. Inside the module are defined properties and methods.
Each module has a module variable that represents the current module.
Module exports property is the interface to the outside world and its value is an object. Module. exports objects have properties or methods that are exported and can be called externally. Unexported contents are private to the module and cannot be accessed externally
When used, it is introduced by require.
Module organization and load logic
Module file organization has two kinds, a single file module and a directory module composed of multiple files.
Modules can also be introduced in two forms, starting with and not starting with a path.
Third Party Modules (NPM)
The third-party module is maintained by the NPM. This section describes how to use the NPM.
NPM in source
npm config set registry https://registry.npm.taobao.org
Global installation
npm i packageName -g
Note: -g = -global
After global installation, you can call the package directly with packageName
Partial installation (for one project only)
-
Initialize the project in the project folder: NPM init
Q&a interactively configure the NPM project to generate package.json. You can also add –yes or -y to the default configuration
-
After the initialization is complete, you can start the installation. You need to add command line parameters:
-
–save / -s: The module package will be placed under Dependencies. Develop and run required modules, such as jQuery
-
–save-dev / -d: the module package will be placed under devDependencies. Module tools that are only dependent on the development environment and are no longer required to run online after development, such as compression modules.
-
-
After installation, you need to select the specific path location of the package to call.\node_modules\. Bin \packageName in the project folder by default
T2: Scaffold tool: Yeoman
Scaffolding tools aid development, helping to quickly create project foundations, providing project specifications and conventions, and enabling code reuse.
Universal scaffold: Yeoman
Specialized scaffolding: Vue-CLI, create-react-app, Angular-CLI (again, more than scaffolding)
Yeoman
Command line tool Yo
Generate different projects by yo management and calling the generator
- Search the website for the generator you need
- Install generator:
npm i -g generatorName
- Create a project: Under the target project folder
yo generatorName
- Run project: under project folder
npm run start
T3: Automated builds
Build: Convert source code into production code.
The build needs are as follows:
- Code needs to be compiled or processed compatible (LESS → CSS, ES6+ → ES5)
- Code needs to be compressed (CSS, JS, HTML, images, etc.) to save bandwidth and speed up loading
- The code needs to do formatting verification, uniform code style.
NPM modules with different functions are used to implement the build we want.
Implementation of automated builds: NPM Scripts
NPM allows you to define script commands using the scripts field in package.json files. Such as:
{
"scripts": {
"foo": "node bar.js"}}Copy the code
The scripts field is an object. Each of its properties corresponds to a command script. Scripts properties can be invoked directly with NPM, which is equivalent to executing the corresponding command on the command line. For example, NPM run foo.
Implement way
Multiple tasks may need to be executed in a single NPM script, and the order in which they are executed needs to be clear.
-
Parallel execution
Task 1**&** Task 2
-
Serial execution series
Task 1 && Task 2
The npm-run-all plugin is required for Windows
The plugin added -p -s command line arguments, corresponding to parallel and serial modes, to be used when run.
Build cases and use of related packages
Build style files
-
Less to CSS (Less plug-in)
lessc
-
CSS format detection (StyleLint plug-in)
-
Configuration:
In the project folder, initialize first: eslint –init will automatically generate the configuration file.eslintrc.json via q&A interaction
The rules in the configuration file can be modified to the style you want to normalize, such as indentation and single and double quotes
-
Use:
- Single file: eslint path/filename.js
- Entire directory: eslint path/dirname
Will prompt warnings or errors according to rules
-
-
Compressed CSS (Minify plug-in)
Build script file
-
ES6+ to ES5 (Babel plug-in)
-
Installation:
Babel has a variety of preset transcoding rules, and the one needed in this example is the most common: babel-preset-env
Install the transcoding rule before using NPM I babel-env -preset -d
-
Configuration: Configure Babel in the project root directory. Babelrc
-
Use:
-
A single file
babel input.js -o output.js
-o
=--out-file
-
Entire folder
babel src -d dist
-d
=--out-dir
-
-
-
Js format detection (ESLint plug-in)
-
Installation:
Installation standard: NPM I-G stylelint-config-standard
-
Configuration: Manually create the configuration file.stylelintrc.json in the project root directory
-
Use:
- Single file:
stylelint path/filename.css
- The entire project:
stylelint **/*.css
- Single file:
-
-
Compression JS (minify plugin) same as above
T4: Automated build tool: Gulp
Further automated builds can be achieved with tools such as Grunt, Gulp, and FIS, of which Gulp is the most popular.
Installation and use of Gulp
-
NPM install -g gulp-cli
-
Initialize the project NPM init –yes
-
NPM install gulp -d
-
Create gulpfile.js in the project root directory
-
In gulpfile.js, create a gulp task
-
Task variable declaration
-
New: Define function constants
All tasks are asynchronous, so callback functions need to be passed in the parameters
-
Gulp.task (‘taskName’, func())
-
-
Job exports: module.exports
The default property of exports can be invoked directly with the gulp command
-
-
Run the gulp task gulp taskName
Combined task #2 in Gulp
Like NPM scripts, Gulp has a way of distinguishing serial from parallel
- Serial:
series(t1,t2,t3)
- In parallel:
parallel(t1,t2,t3)
The two can be nested with each other on multiple levels to achieve a more complex order of execution
File operation #3
File operations in Gulp are stream-based
-
Read stream/source: SRC ()
Parameters:
- Source file *, URL string
- Configuration, object
- Base: preserves the directory structure under this location, url string
-
Write to stream/target: dest()
-
Pipe, pipe ()
e.g.
const { src, dest } = require('gulp');
exports.default = () = > {
return src('src/styles/main.less', { base: 'src' }).pipe(dest('dist'))}Copy the code
【 Case 】 Automated construction using Gulp and related plug-ins
Build CSS style file #4
Gulp-less, gulp-clean-css, and gulp-rename are used to convert a less file to a CSS file, compress and rename the file in one step.
- in
gulpfile.js
Add plug-in dependencies - Create a new task, between source and destination, using pipes
pipe()
Invoke the plug-in. Each call requires a pipe that can be called continuously. - The export task
CSS hack plugin: Autoprefixer #5
Use the gulp-Autoprefixer plugin to create CSS prefixes for different browsers, using data from caniuse.com
It should be processed after transformation and before compression.
Build the JS script file #6
Gulp-babel, gulp-uglify and gulp-rename plug-ins are used to reduce the version, compress and rename JS files.
A call to gulp-babel writes the transformation rule to a configuration object as an argument:
- Old version:
{ presets: ['@babel/env'] }
- The new version:
{ presets: [babel/presets/env] }
Build the HTML page file #7
Compression: gulp – htmlmin
Gulp-htmlmin takes a configuration object such as {collapse: true, minifyCSS: true, minifyJS: true} to compress HTML whitespace and inline styles and scripts.
Build image file #8
gulp-imagemin
File cleanup #9
Requirement: Remove redundant files before build
del
“Comprehensive”
Combine the above build operations into one task:
series(clean, parallel(style, script, html, img))
Clear the target folder first, then execute the parallel construction of HTML, CSS, JS, and image files.
Development server #10
browser-sync