Javascript based

1. Differences between arrow functions and ordinary functions

1.1 cannot be called by the new keyword. There is no prototype

  • New cannot be used. Arrow functions have no Construct method and cannot be used as constructors
  • You can’t call a function with the new keyword, there’s no need to build a prototype, so there’s no prototype property inside the arrow function, so the arrow function has no prototype
  • New. Target, which is new in ES6, also does not have access to stereotype properties via super
    // An example of the difference between arrow functions and normal functions
    var Foo = () = > {};
    console.log(Foo.prototype); // undefined
    Copy the code

1.2 It is not possible to change the this binding, which is determined by the outer non-arrow functions, so using call, apply, and bind will not affect it

  • Function (order of priority from highest to lowest)
    1. Use the new keyword when calling a function, where this is a brand new object.
    2. If the apply, call, or bind methods are used to call and create a function, this is the object passed to those methods as an argument.
    3. When a function is called as a method in an object, this in the function is the object on which the function is called.
    4. If the calling function does not conform to the above rules, then the value of this refers to the global object.
    5. In browser environments this points to the window object, but in strict mode ‘use strict’ this is undefined.
  • Arrow function
    • No matter how or where it is executed, the this value inside the arrow function is always equal to the this value of the nearest external function. In other words, arrow functions parse this lexically; arrow functions do not define their own execution context.
    • If you’re familiar with React, you’ll need to bind this if you want to use a method in a class
    • Copy the code

    const obj = { value: 2, callback: Function (arr) {var self = this} function(arr) {var self = this} function showThis() {console.log(self.value)} showThis() } } const obj2 = { value: 2, callback: function(arr) { showThis = () => { console.log(this.value) } showThis() } } obj.callback() // 2 obj2.callback() // 2

    Copy the code

1.3 does not support arguments, so depending on the scope chain, you will get arguments for the outer function

  • The conventional function
    • There is an array object of arguments class that contains all the arguments to the function
    • Often used when we do not specify the parameters
  • Arrow function
    • Arrow functions are array-like objects that do not support arguments
    • If you use it in an arrow function, the search rules of the scope chain will query to the nearest non-arrow function, and then you will actually use arguments from the non-arrow function
    • For this reason, ES6 also provides the operation of parameters in this indeterminate case, as shown in the following example
    / /... Args converts an indefinite parameter to an array,
    // Use this only once and at the end of all arguments
    const add = (. args) = > {
         return args.reduce((cur, i) = > cur + i, 0)
    }
    add(5.10.15) / / 30
    Copy the code

1.4 Naming parameters repeatedly is not supported

  • Arrow functions do not support repeated named arguments in either strict or non-strict mode, and traditional functions do not support repeated named arguments only in strict mode.
var a = (b, b) = >{
    b = 100
    console.log(this)
    console.log(b)
} // Uncaught SyntaxError: Duplicate parameter name not allowed in this context
Copy the code

1.5 Implicit Return

  1. There is always a hidden return value inside the functionfunctionIf you don’t define anything, it actually returns by default, rightundefinedI understand that this terminates the execution of the function in code
function noReturn() {
  console.log('aaa')
  return // Do not write this manually, default is not written
  // If you don't have a function that needs a return, it automatically adds one to you
}
Copy the code
  1. The arrow function saves a return, which is suitable for cases where there is only one line of code in the function, and multiple lines need to be written
    • If return is a value, {} is not required.
    • If you return a literal, add ()
      const add = (a, b) = > a + b
      const obj = () = > ({ a: 1 })
      Copy the code

2. Array method sorting

The method name Corresponding to the version function Whether the original array changes
concat() ES5- Merge arrays and return the merged data n
join() ES5- Using a delimiter, turn the array into a string and return it n
pop() ES5- Deletes the last bit and returns the deleted data y
shift() ES5- Deletes the first digit and returns the deleted data y
unshift() ES5- To add one or more digits to the first digit, return the length y
push() ES5- Adds one or more data bits to the last bit, returning the length y
reverse() ES5- Invert the array and return the result y
slice() ES5- Intercepts an array at the specified location and returns n
sort() ES5- Sort (character rules) and return results y
splice() ES5- Deletes a specified location and replaces it, returning the deleted data y
toString() ES5- Convert directly to a string and return n
valueOf() ES5- Returns the original value of an array object n
indexOf() ES5 Query and return an index of the data n
lastIndexOf() ES5 Reverse the query and return the index of the data n
forEach() ES5 The callback function takes three arguments, value, index, and self, and iterates through all the items in the array. ForEach has no return value n
map() ES5 As with forEach, the callback function returns data that forms a new array to be returned by Map n
filter() ES5 As with forEach, the callback function returns a Boolean value that is true to form a new array returned by filter n
every() ES5 As with forEach, the callback returns booleans, all true, and every returns true n
some() ES5 As with forEach, both callback functions return booleans as long as one of them is true and some returns true n
reduce() ES5 Merge, with forEach, iterates through all the items in the array and builds a final value that is returned by Reduce n
reduceRight() ES5 Reverse merge, with forEach, iterates through all the items of the array and builds a final value, returned by reduceRight n
## 3. Array shallow copy method
The serial number way example instructions
—— ———— ————
1 concat let res = arr.concat(); Concatenated array returns a new array
2 slice let res = arr.slice(); Returns selected elements starting from 0 to ending by default
3 deconstruction let res = […arr]; Creates a new array assigned to the value of the current array
4 Deconstruction 2 let […res] = arr; Same as above
5 map let res = arr.map(i=>i); Iterating through the array of numbers returns elements to res one by one
6 Array.of let res = Array.of(… arr); This method returns a bunch of numbers as an array

2.Webpack

2.1 WebPack Performance Optimization – Build speed

1. Optimization of Babel – loader

module: {
	rules: [{test: /\.js$/,
          use: ['babel-loader? cacheDirectory'].// Enable caching
          include: path.resolve(__dirname, 'src') // Specify the scope
          // // Select either include or exclude
          // exclude: path.resolve(__direname, 'node_modeles')}}]Copy the code

2. IgnorePlugin Ignores useless files

  • Use IngorePlugin to ignore useless files

For example: Moment supports multiple languages, how do you only introduce Chinese modules?

// Ignore the /locale directory under moment
new webpack.IgnorePlugin(/\.\/locale/./moment/)

// Dynamically introduce language packs into business code
import 'moment/locale/zh-cn'
Copy the code

3. NoParse avoids repeated packaging

  • NoParse avoids repeated packaging
module: {
  noParse: [/react\.min\.js$/]
}
Copy the code
  • Differences between IgnorePlugin and noParse
    • IgnorePlugin is not introduced directly, not in the code
    • NoParse (similar to vue.min.js already modularized) is introduced, but not packaged

4. Happypack Multi-process packaging tool

  • JS single thread, enable multi-process packaging
  • Improved build speed (especially on multi-core cpus)
    const HappyPack = require('happypack')
    
    Module. rules - Pass the.js file to the HappyPack instance whose id is label
    {
      test: /\.js$/,
      use: ['happypack/loader? id=babel']}// Step 2 happyPack enables multi-process packaging
    new HappyPack({
     // Use a unique identifier id to indicate that the current HappyPack is used to process a specific class of files
     id: 'babel'.// How to handle.js files with the same usage as Loader configuration
     loaders: ['babel-loader? cacheDirectory']})Copy the code

5. ParalleUglifyPlugin multi-process code compression

  • Webpack has built-in Uglify tools to compress JS
  • JS single thread, open multi process compression faster
  • Just like happyPack, multiple processes
    ParallelUglifyPlugin is used to compress the output JS code in parallel
    const ParallelUglifyPlugin = require('ParallelUglifyPlugin')
    
    new ParallelUglifyPlugin({
      // The argument passed to UglifyJS
      // Use UglifyJS compression again, just to help start multi-process)
      uglifyJS: {
        output: {
          beautify: false.// Most compact output
          comments: false // Delete all comments
        },
        compress: {
            // Delete all 'console' statements, compatible with Internet Explorer
            drop_console: true.// Inline variables that are defined but used only once
            collapse_vars: true.// Extract static values that occur multiple times but are not defined as variables to reference
            reduce_vars: true}}})Copy the code

6. Automatically refresh

  • Automatic refresh: the whole page is refreshed, the speed is slow
  • Automatic refresh: State is lost (data in the form is lost)

7. Hot update

  • Hot update: the new code takes effect, the web page is not refreshed, and the status is not lost
  • HotModuleReplacementPlugin plug-in in webpack/lib
// Set index in entry
 index: [
    'webpack-dev-server/client? http://localhost:8080/'.'webpack/hot/dev-server',
    path.join(srcPath, 'index.js')]2 / / configurationIn the pluginsnew HotModuleReplacementPlugin()

3 / / configurationIn devServer add hot:true

4 / / configurationBusiness to addmodule.hot to determine which ranges need to trigger hot updatesCopy the code

8. DllPlugin Dynamic link library plug-in

  • Use reasons
    1. Front-end frameworks Vue and React are bulky and slow to build
    2. Relatively stable, not often upgraded version
    3. Build the same version only once, not every time
  • Webpack already has built-in DllPlugin support
    • DllPlugin – Package out DLL files
    • DllReferencePlugin – Use DLL files
  • use
// Create a new webpack.dll.js file
const path = require('path')
const DllPlugin = require('webpack/lib/DllPlugin')
const { srcPath, distPath } = require('./paths')

module.exports = {
  mode: 'development'.// JS executes entry files
  entry: {
    // Put the React related modules into a separate dynamic link library
    react: ['react'.'react-dom']},output: {
    [name] is the name of the current dynamic link library.
    // React and polyfill configured in Entry
    filename: '[name].dll.js'.// Put the output files in the dist directory
    path: distPath,
    // Store the global variable name of the dynamic link library, for example, _dll_react
    // _dll_ is added to prevent global variable collisions
    library: '_dll_[name]',},plugins: [
    / / access DllPlugin
    new DllPlugin({
      // The global variable name of the dynamically linked library needs to be the same as that in output.library
      // The value of this field is the value of the name field in the output manifest.json file
      // For example, react. Manifest.json has "name": "_dll_react"
      name: '_dll_[name]'.// The name of the manifest.json(index file) file that describes the output of the dynamic link library
      path: path.join(distPath, '[name].manifest.json'),})],}Copy the code
  • DllReferencePlugin (remember to ignore the packaged node_modules DLL code in rules)
 	plugins: [
        new webpack.DefinePlugin({
            // window.ENV = 'production'
            ENV: JSON.stringify('development')}),// Third, tell Webpack which dynamic link libraries are used
        new DllReferencePlugin({
            // Describes the react dynamic link library file contents
            manifest: require(path.join(distPath, 'react.manifest.json')),})],Copy the code

2.2 Webpack Performance optimization – Generate code

role

  1. It’s going to be smaller
  2. Reasonable subcontracting, no repeated loading
  3. Faster and less memory usage

Optimize the way

  1. Base64 encoding for small images (set the urL-loader to options.limit for images)
  2. Bundle + hash ([name].[contentHash:8].js)
    • ContentHash :8 is an 8-bit hash value calculated based on the content
  3. Lazy loading () = > import (‘ ‘)
  4. Extract common code splitChunks: common code and tripartite code
  5. IgnorePlugin: Ignores the file and does not introduce packaging
  6. Acceleration with CDN:
    • Add publicPath to output
    • Add publicPath to options in urL-loader to set the image
  7. The use of production
  8. Scope Hosting
    • Changed the packaging scope to make the occupying update write faster packaging
  9. Open the gzip