directory
Introduction to 1,
1-1 front-end development
modular
CommonJS
Advantages: Code can be reused in nodeJS environment
Third-party modules distributed through NPM adopt the CommonJS specification
Disadvantages: Tools must be used to convert to ES5, otherwise it cannot be executed in a browser environment
AMD is also a JS modularization specification, which differs from CommonJS in that it uses an asynchronous way to load dependent modules. Requirejs is the most representative implementation
Advantages:
Can run directly in the browser without converting code
Dependencies can be loaded asynchronously
Multiple dependencies can be loaded in parallel
Runs in Node and browser environments
Disadvantages:
JS native environment does not support AMD, you need to enter the AMD library to use
ES6 modular
The ultimate modularity solution, but it does not run in most JS environments and must be converted to ES5 via tools
1-2 Common building tools and comparison
Front-end engineering
- Build is the transformation of source code into JS, CSS, and HTML code that can be published online and executed
- Code conversion: TS compilation into JS and so on
- File optimization: compress JS, merge pictures and so on
- Code segmentation: Extract common code and asynchronously load the code that does not need to be executed on the first screen
- Module merge: Merge modules into a file
- Auto refresh: Listen to local source code, automatically rebuild, refresh the browser
- Code verification: automatic verification of code compliance
- Automatic release
Build tools
Npm Script is a task executor, and each attribute in scripts corresponds to a shell Script
Grunt is also a task-taker, an evolved version of NPM Script
Gulp is a stream-based automated build tool, but it’s not integrated enough to work out of the box
Webpack is a package modular JS tool, in Webpack everything module, through the Loader conversion file, Plugin injection dog, finally output file
Rollup is similar to Webpack, with the highlight of es6 Tree Shaking to remove useless code, but the ecosystem is not perfect
Use Loader, Plugin, DevServer
Loader to use
- Webpack does not support parsing CSS files
- Loader, which can be seen as a file translator, configures a set of rules in module.rules
- The Loader execution order is from the back to the front of the array configured for the use property
- The general principle of style-loader is to store CSS content as JS string, and dynamically insert style label through DOM when web page executes JS
The Plugin to use
- Use to extend webPack functionality and inject hooks into the build process, giving WebPack a lot of flexibility
- A plugin is an array, and each entry is an instance of a plugin
DevServer use
- Can provide HTTP service
- Monitor file changes and automatically refresh, achieve real-time preview
- Support SourceMap for easy debugging
- DevServer communicates through the WebSocket protocol
- Module hot replacement, by replacing an older module with a newer one without reloading the entire page
The core concept
- Entry: Entry, the first step in the build that Webpack performs will start with Entry, which can be abstracted into input
- Module: Module, in Webpack everything is a Module, a Module corresponds to a file. Webpack recursively finds all dependent modules starting from the configured Entry.
- Chunk: a Chunk is a code block. A Chunk is composed of multiple modules for code merging and splitting
- Loader: code block. A Chunk is composed of multiple modules for code merging and splitting
- Plugin: Extension Plugin that injects extension logic at specific points in the Webpack build process to change the build result or do what you want
- OutPut: Outputs the result after Webpack has gone through a series of processes and produced the final desired code
2, configuration,
2-1 Entry Output Module Resolve Plugins DevServer
Entry
Entry is the entry to the configuration module, which can be abstracted as input, and Webpack performs the first step of construction by searching and recursively resolving all the modules that the entry depends on.
Output
How does the configuration output the desired code
Filename: [id] [name] [8] hash: [8] chunkhash: js
PublicPath: Indicates the URL prefix published to online resources. The value is a string. The default is an empty string “, that is, a relative path.
CrossOriginLoading: Dynamically inserting a script tag into HTML to load asynchronous resources. Anonymous (default) does not carry cookies, use-credentials carry cookies
Module
How is the module configured
Rules: configures the read and parse rules of the module, which is usually used to configure the Loader
Module: {rules: [{// hit JavaScript file test: /.js$/, // convert JavaScript files with babel-loader //? CacheDirectory represents the parameter passed to babel-loader for caching Babel compilation results to speed up recompilation use: ['babel-loader? CacheDirectory '], // only hits js files in SRC to speed up Webpack search include: Path.resolve (__dirname, 'SRC ')}, { /.scss$/, // Uses a group of loaders to process SCSS files. ['style-loader', 'css-loader', 'sass-loader'], // exclude files in node_modules: Path. resolve(__dirname, 'node_modules'),}, {// Use file-loader to load test for non-text files: /.(gif|png|jpe?g|eot|woff|ttf|svg|pdf)$/, use: ['file-loader'], }, ] }Copy the code
Resolve
Resolve configures how Webpack finds the files for the modules that depend on it, starting from the configured entry module.
Plugins
Plugin is used to extend Webpack functionality
DevServer
Hot: the module hot replacement function enables real-time preview without refreshing the page
Inline: Control code builds enough to refresh the page automatically
HistoryApiFallback: An HTML file is returned if any route is hit
ContentBase: Configures the DevServer HTTP server file root directory
Headers: injects the HTTP response header
Host: 0.0.0.0 can be accessed by other Lans
Port: indicates the port number
HTTPS: automatically generates an HTTPS certificate
2-2 Other configuration items
Target
Target environment: Web (default), Node, webworker……
Devtool
How do I generate the Source Map
Watch & WatchOptions
When DevServer is used, listening mode is turned on by default
Externals
Tell Webpack that the JavaScript runtime environment already has those global variables built in and that you don’t need to package them into your code to use them directly
2-3 Overall structure configuration
const path = require('path'); Module.exports = {// entry stands for entry, and Webpack performs the first build from entry, which can be abstracted as input. / / type can be a string | object | array entry: '/ app/entry', / / only one entrance, entrance only one file entry: ['/app/entry1 ', '/ app/entry2'], / / only one entrance, the entrance there are two file entry: {/ / have two entrance to a: '/ app/entry - a', b: ['./app/entry-b1', './app/ entry-B2 ']}, // How to output the result: how to output the final desired code after a series of processing in Webpack. Output: {// The directory where the output file is stored. It must be an absolute path of type string. Resolve (__dirname, 'dist'), // Output file filename: 'bundle.js', // full name filename: '[name].js', // When multiple entries are configured, use the name template to generate different file names for different entries filename: '[chunkhash].js', // Generate the file name based on the hash value of the file content, used by the browser to cache the file for a long time // The URL prefix of all resources published online, string publicPath: '/assets/', // to the specified directory publicPath: '", // to the root directory publicPath: 'https://cdn.example.com/', // to the CDN // the name of the export library, string type // without it, the default output format is the anonymous execute now function library: 'MyLibrary', // Export library type, enumeration type, The default is/var/can be umd | umd2 | commonjs2 | commonjs | | amd this | var | assign window | | global | json, libraryTarget: 'umd', // whether to include useful file path information to the generated code, Boolean type pathInfo: true, // The name of the additional Chunk file chunkFilename: '[id].js', chunkFilename: '[chunkhash].js', // JSONP async load resource callback function name, need to use jsonpFunction with server: 'myWebpackJsonp', // Generated Source Map file name sourceMapFilename: '[file]. The map', / / the browser in the developer tools shows the source module name devtoolModuleFilenameTemplate: 'webpack:///[resource-path]', // How to load cross-domain resources asynchronously crossOriginLoading: 'use-credentials', crossOriginLoading: 'anonymous', crossOriginLoading: false,}, // Configure module related module: {rules: [// configure Loader {test: Resolve (__dirname, 'app')], exclude: /.jsx?$/, // include: [// path. Resolve (__dirname, 'app')], exclude: Path. resolve(__dirname, 'app/demo-files')], use: [// use Loader in sequence, execute 'style-loader' from back to front, // use Loader name directly {Loader: 'css-loader', options: }}]},], noParse: [// special-library.js$/ / with re matching],}, // configure plugins: [], // configure the rule to find modules resolve: {modules: [// find the root directory of the module, array type, default node_modules root directory 'node_modules', path.resolve(__dirname, 'app')], extensions: ['. Js', 'json', 'JSX', 'CSS'], / / module suffix alias: {// module alias configuration, used to map modules // map 'module' to 'new-module', the same 'module/path/file' will be mapped to 'new-module/path/file' 'module': 'new-module', // map 'only-module' to 'new-module' with the ending $, // But unlike above, 'module/path/file' will not be mapped to 'new-module/path/file' 'only-module$': 'new-module',}, alias: [// alias also supports arrays for more detailed configuration {name: 'module', // The old module alias: 'new-module', // new module/ / whether only modules will be mapped, if true only 'module' will be mapped, if false 'module/inner/path' will be mapped onlyModule: }], symlinks: true, // Whether to follow the soft link to find the module's path descriptionFiles: ['package.json'], // mainFields: ['main'], // whether the enforceExtension statement is mandatory, and the file suffix is enforceExtension: false, // Whether the enforceExtension statement must be enforceExtension}, // Output file performance check configuration Performance: {hints: Hints: 'error', // Displays warning hints: 'error', // displays error hints: False, // Turns off performance check maxAssetSize: 200000, // Maximum file size (bytes) maxEntrypointSize: 400000, // Maximum entry file size (bytes) assetFilter: Function (assetFilename) {/ / filter file to check the return assetFilename. EndsWith (' CSS ') | | assetFilename. EndsWith (' js'); }}, devtool: 'source-map', // configure source-map context: __dirname, // the root directory used by Webpack, string must be the absolute path // Configure the running environment of the output code target: 'web', // browser, default target: 'webworker', // webworker target: 'node', // node. js, load Chunk code target with 'require' statement: 'async-node', // node. js, async load Chunk code target: 'node-webkit', // nw.js target: 'electron ', // electron, main thread target: 'electron-renderer', // electron, render thread externals: {// Use global variables provided by the JavaScript runtime environment jquery: 'jquery', stats: {// Console output log control assets: true, colors: true, errors: True, errorDetails: true, hash: true,}, devServer: {// DevServer-related configuration proxy: {// Proxy to back-end service interface '/ API ': 'http://localhost:3000'}, contentBase: path.join(__dirname, 'public'), // configure DevServer HTTP server root directory compress: HistoryApiFallback: true, // Whether to enable gzip historyApiFallback: true, // Whether to develop HTML5 History API pages hot: true, // Whether to enable module hot replacement HTTPS: False, // whether to enable HTTPS mode}, profile: true, // Whether to capture Webpack build performance information to analyze the cause of poor build performance Cache: false, // Whether to enable caching to improve build speed watch: True, // Whether to start watchOptions: {// Listen mode options // do not listen to files or folders, support regular matching. Ignored: /node_modules/. // aggregateTimeout: 300ms. // aggregateTimeout: 300ms. Poll: 1000}, poll: 1000}, poll: 1000}Copy the code
3, in actual combat
3-1 use ES6
Two things: THE ES6 syntax is implemented in ES5, and the new API injects Polyfill
Babel: For both of those things
Access: Access through babel-loader
3-2 use TS
Create the tsconfig file
Use the awesome – typescript – loader
Use PostCSS 3-3
PostCSS is written in JavaScript and runs on Node.js. When it is started, it reads the required configuration from the postcss.config.js file in the directory
3-4 Generate HTML for single-page applications
web-webpack-plugin
3-5 Construction of isomorphic applications
The ultimate goal of building a homogeneous application is to build two pieces of JavaScript code from a source code for the project, one for running in the browser and one for running the rendered HTML in the Node.js environment.