What is NodeJS? A JavaScript runtime based on the Chrome V8 engine, which simply executes JavaScript code. Browsers can execute JS, NodeJS can execute JS, and the main engines are V8 engines. At first glance, there may seem to be no difference, but in fact there is a huge difference. Here is my understanding for your reference:
As mentioned in the second article of this series, front-end applications can be deployed in two ways: static construction and server-side rendering. In either case, the browser will eventually get the HTML, CSS, JS and other resources processed by us. The final JS code is executed when the HTML is parsed. Note that the user’s browser executes the code. Users from all over the world use the browser to download the front-end code of our Web application and execute it locally. At this time, the running environment of the front-end code is the browser, and its functions are greatly limited.
NodeJS, on the other hand, is run locally on the server or by the developer, which means that NodeJS can do a lot more than a browser, which is a subset of NodeJS. Because you can run an interface less browser in NodeJS.
The same JS code may not run in both environments, depending on whether you use global variables that are only available in the current environment. Typical global variables in browsers are window and document. Typical global variables in NodeJS are process and __dirname. Other NodeJS methods can be introduced in the CommonJS module system.
Application scenarios
Based on the power of NodeJS, let’s take a look at the application scenarios, the built-in modules used, and the hot technology stacks in these scenarios:
Build the server application
NodeJS works well in IO-intensive scenarios thanks to its event-looping mechanism, but the biggest advantage of using NodeJS to build servers is that you can write front-end and back-end code in one language. Language learning and switching come at a cost, and the efficiency and comfort of unified language development is enormous. In terms of performance and community ecology, there is no obvious advantage over other languages such as Java and GoLang. It can be said that NodeJS is suitable for full-stack development, IO intensive scenarios, and server-side rendering front-end applications.
Hot technology stack: Nex.js with java-like development experience, Egg.js with alibaba team focusing on enterprise-level framework, Fastify focusing on performance, Express with mature ecosystem of old framework
The built-in modules include HTTP, HTTPS, and URL
Build client applications outside of the browser
The advantage of writing client applications with NodeJS is that you can develop the interface in the same way as writing Web applications, and at the same time have the ability to call the operating system.
Hot tech stack: Electron builds a cross-platform desktop APP, Johnny Five focuses on iot application development, and a multi-platform compatible hardware framework
It mainly involves built-in modules: OS and FS
Build a front-end development tool chain
As a scripting language, JS is also suitable for creating front-end development tool chains. We can use tools to do batch processing before we put code online, such as compressing obfuscated code, dealing with compatibility issues, injecting environment variables, converting file contents, checking code style, and so on
Hot tech stacks: community-leading packaging tool WebPack, gulp known for automation and enhanced workflows, rollup more focused on packaging JS, code style validation tool ESLint, template processing tool EJS, unit testing tool JEST, and more
It mainly involves built-in modules: FS, STREAM, readline
Utility tools Serve
Recommend you a very practical static file service startup tool: serve, local start HTML debugging environment is very convenient, assuming our directory is like this:
- src
- detail
- index.html
- index.js
- index.css
- home
- index.html
- index.js
- index.css
Copy the code
We can use serve like this:
# installation serve
npm i serve -g
Switch to the SRC directory
cd src
# Start local service
serve
Copy the code
At the command line will output has run local static service, open the http://localhost:3000 or http://localhost:3000/home/index can see directory or page. Note: Because serve exposes all directories under the startup path, it should not be used in online environments.
WebAssembly
When running code that runs into performance bottlenecks, consider compiling to.wasm in a high-performance language (C++, Rust) to introduce execution in NodeJS. Official tutorial: Using WebAssembly
Webpack
Webpack is a built-in packaging tool for create-React-app and VUE-CLI. Its community ecosystem is very mature, with a variety of loaders and plugins that can process the code written by developers and ultimately output static resources that can be deployed or start a local development environment. The most obvious ones are.vue files,.less files, and.ts files. If you don’t want your code to be processed, you may have to write spec compliant HTML/CSS/JS files inefficiently. Here we introduce some knowledge and practical skills of Webpack5:
concept
The official website introduces seven concepts :entry, output, loader, plugin, mode, Browser compatibility, environment. Let’s remember two :entry and output, namely the entry and output. Webpack’s work is pure, as shown in the first image on the website, you give me a bunch of stuff and I just make it HTML/CSS/JS/JPG for the browser to execute. For example, when you eat noodles and cake, it’s all digested into sugar protein. And how to deal with, the most important is to rely on all kinds of loader and plugin.
loader
Loader is used to preprocess files, input a file content, output one or more files. Loaders are simple, chain-callable, modular, and stateless. A group of Loaders pass the results down in sequence, and the last loader returns the JS file that meets webPack requirements.
Common loaders are:
- Babel-loader is responsible for converting ES2015+ code to ES5 and supporting JSX syntax
- Ts-loader converts TypeScript 2.0+ to JS code
- Vue-loader converts.vue code to JS code
- Less-loader converts. Less codes to CSS codes. Less-loader is used together with CSS-loader and style-loader
plugin
Webpack has a very powerful plug-in loading mechanism that can do anything NodeJS can do. Webpack calls the plug-in and passes the Webpack Compiler as a parameter at the appropriate compile life cycle, depending on the configuration. That is, the plug-in can be executed at any time during the packaging process and has access to all the information that Webpack exposes during the process. The Webpack compilation process has over twenty lifecycle hook functions. Let’s look at common plugins to see what can be done:
- Html-webpack-plugin – Generate HTML files and inject them into the package results
- Copy -webpack-plugin – Copies static resources to the specified directory
- Clean -webpack-plugin – Cleans up the specified directory
- Terser-webpack-plugin – Zip JS files
- Webpack-bundle-analyzer – Analyzes the size of packed files
- Webpack-dev-server – Starts the local development environment service
- Webpack -hot- Middleware – Development environment file changes hot updates
Practical skills
- Use ProvidePlugin to inject global variables, such as jquery, lodash or process.env.node_env
- How to improve the packaging speed: Filter files processed by the loader. For example, configure the babel-loader option to exclude files. Configuring cacheDirectory to cache processing results to the file system to avoid repeated processing.
- When project A needs to reference A module from project B, you can use the module federation feature to cross-project reference.
- For officially initiated single-page applications such as Vue and React, if there are several unrelated modules in a project, multiple entries can be added to output different modules into different HTML files to form multiple single-page application modes. It can well reduce the packing volume and accelerate the loading speed of each module.
Dependency management: NPM, CNPM, YARN, and PNPM
When we use a tool library in the community ecosystem, we use dependency management tools, such as the official NPM. Record the dependency libraries and version numbers in package.json, and install using the NPM install command. Package.lock. json files are generated to record information about the dependencies and other libraries they depend on, ensuring that everyone installs the dependencies with the same results.
Dependency installation FAQ handling:
- The dependencies are stored in node_modules. If you have problems with the installation and want to reinstall it, you can delete this directory.
- You can copy the node_modules directory to the unsuccessful node_modules directory.
- For long-term maintenance projects, a fixed version number should be specified in package.json and should not be used
^ 16.8.0
或~ 16.8.0
I’m going to write a definite16.8.0
To avoid unnecessary updates. If you can confirm updates, you can directly change the fixed version number. - If the installation fails, you can use NVM to switch the Node version, or switch to the domestic image source, or use scientific Internet to try again
Image source
NPM is the official dependency management tool. In daily use, it is recommended to switch to a domestic image source to speed up the dependency installation. Run the following command to switch to a Taobao image source address:
npm config set registry https://registry.npm.taobao.org
Copy the code
CNPM is suitable for domestic use. Yarn and PNPM have optimized installation speed. No matter which one is used, it is hoped that the corresponding dependency can be installed. There should be a unified reliance on installation tools within a team.
Fourth, front-end editor, debugging tools use skills
— small tail — my name is ge shengming, good at the front end, have ideas have questions welcome private discussion ^_^