webpackgrunt,gulpThe difference between

Grunt and GULp are task-based tools: they automate a given task, like an assembly line, putting resources on it and processing them through plugins. They have active communities, rich plugins, and easy workflows.

Webpack is a tool based on modular packaging: WebPack treats everything like a module, and when webPack processes a program, it recursively builds a dependency graph that contains every module the application needs, and then packages all the modules into one or more bundles.

So these are two very different types of tools, and NPM Script can also create a task flow.

webpack,rollup,parcelPros and cons

Webpack is great for large and complex front-end site builds: WebPack has a powerful loader and plug-in ecosystem, and the packaged file is really just an instant-execute function that takes a parameter (module object), the key is the path to each module, and the value is the content of the module. Immediate functions internally handle references between modules, execution modules, etc., and are more suitable for complex file-dependent application development.

Rollup is suitable for packaging base libraries such as Vue, D3, etc. Rollup packs modules into a single file and tree-shaves out useless code to minimize the size of the code, but rollup is better suited for library development because it doesn’t have as much code splitting, loading on demand, and so on as WebPack.

Parcel is suitable for simple experimental projects: it has a low threshold for quick results, but poor ecology and incomplete error messages are issues, and is not recommended except for some experimental projects.

commonloader

  • file-loaderOutput the file to a folder, referencing the input file with a relative URL in the code
  • url_loaderSimilar to file-loader, you can base64 file content into your code even if the file is very small
  • source-map-loaderLoad additional Source Map files to facilitate breakpoint debugging
  • image-loaderLoad and compress image files
  • babel-loaderConvert ES6 to ES5
  • css-loaderLoading the CSS supports features such as modularization, compression, and file import
  • style-loaderThe CSS code is injected into JavaScript, and the CSS is loaded through DOM manipulation
  • eslint-loaderJavaScript code is checked with ESLint
  • html-minify-loaderCompressed HTML

loaderfeatures

  • Loader: evaluate/execute from right to left
  • Loaders support chained delivery, and each loader in the chain applies the transformation to the processed resource
  • Loader can also display the specified inline
  • The Loader can be synchronous or asynchronous
  • Loader runs in Node.js and can perform any operation that Node.js can
  • Loader can be configured using the Options object
  • Except for the usual passpackage.jsonTo export an NPM module to loader, you can also export the NPM module to loadermodule.rulesUses the Loader field to reference a module directly in
  • Loader can generate additional arbitrary files

commonplugin

  • define-pluginDefining environment variables
  • html-webpack-pluginSimplify HTML file creation
  • uglifyjs-webpack-pluginCompress ES6 code with UglifyES
  • webpack-parallel-uglify-pluginMulti – core compression, improve compression speed
  • webpack-bundle-analyzerVisualize the size of the WebPack output file
  • mini-css-extract-pluginThe CSS is extracted into a separate file and can be loaded on demand
  • clean-webpack-pluginClean up the /dist folder before each build

loaderpluginThe different

Effect of different

Loader is the loader. Webpack treats all files as modules, but WebPack can only parse JS and JSON files natively. If you want to package other files, you will use Loader. Loader allows WebPack to load and parse non-javascript files.

Plugin is a plug-in. You can extend the functionality of WebPack to make it more flexible. A number of events are broadcast during the webPack run cycle, and the Plugin can listen for these events and change the output when appropriate through the API provided by WebPack.

Use different

Loader is configured in module.rules, that is, it exists as a parsing rule for modules. The type is array, and each item is an Object that describes what type of file is loaded with and what parameters are used.

Plugins are configured separately in plugins. Each item is an instance of plugin, and the parameters are passed in through the constructor.

bundle,chunk,module

Bundle A file packaged by webpack

chunkCode block, onechunkIt is composed of multiple modules for code merging and splitting

moduleIndividual modules under development,webpackEverything is a module, one module corresponds to one file

webpackBuild process of

The running flow of WebPack is a serial process that executes the following flow once from start to finish:

  1. Initialization parameters: read and merge parameters from configuration files and script statements to get the final parameters;
  2. Start compiling: initialize the Compiler object using the parameters obtained in the previous step, load all the configured plug-ins, and execute the object’s run method to start compiling.
  3. Determine entry: find all entry files according to the entry in the configuration;
  4. Module compilation: Starting from the entry file, call all configured Loader to translate the module, find out the module that the module depends on, and then recurse this step until all the files that the entry file depends on have gone through this step.
  5. Complete module compilation: Step 4 After all modules are translated, the final content of each module after translation and their dependencies are obtained;
  6. Output resources: assemble chunks containing multiple modules one by one according to the dependency between the entry and modules, and then convert each chunk into a separate file and add it to the output list. This step is the last chance to modify the output content.
  7. Output complete: After determining the output content, determine the output path and file name based on the configuration, and write the output content to the file system.

In the above process, WebPack will broadcast a specific time at a specific point in time, the plug-in will execute a specific logic after listening to the event, and the plug-in can call the API provided by WebPack to change the running result of WebPack.

Have you ever written it yourselfloaderplugin

The loader escapes the read source file into the new file, and each loader converts the source file to the desired shape through a chain operation.

writeloaderThere’s a single rule to follow, every single oneloaderI only do one kind of escape,loaderGet the content of the source file (source), the processed content can be output by way of return value after processing, or can be calledthis.callback() Method returns the content towebpack. You can also go throughthis.async()To generate acallbackDelta function, and then use thiscallbackOutput the processed content. Webpack also prepares development for developersloaderSet of utility functionsloader-utils

plugin Listen for events broadcast during a WebPack run and change the output through the WEBPack API when appropriate.

webpackHow is hot update done

Hot update is also called Hot Module Replacement, or HMR for short. This mechanism allows you to replace the old module with the new one without refreshing the browser.

Hot update inserverThe client andclientBoth ends are treated

  1. inwebpackwatchIn this mode, a file in the file system is changed.webpackListen for file changes, recompile and package the module according to the configuration file, and pass the packaged code through a simpleJavaScriptObjects are stored in memory.
  2. webpack-dev-serverwebpackInterface interaction between this step, mainlydev-serverThe middlewarewebpack-dev-middlewarewebpackThe interaction between,webpack-dev-middlewarecallwebpackExposed apis monitor code changes and tellwebpackPackage the code into memory.
  3. webpack-dev-serverMonitoring file changes is not monitoring code changes for repackaging. When configured in the configuration filedevServer.watchContentBasetrueThe time,serverIt listens for changes in static files in these configuration folders and notifies the browser for application changeslive reloadHere is the browser refresh.
  4. wecpack-dev-serverThe code works mainly throughsockjs(webpack-dev-serverCreate one on the browser side and the server sidewebsocketThe long connection willwebpackThe status information for each phase of the build package is communicated to the browser side, as well as in Step 3serverListen for static file changes. The browser side is based on thesesocketMessages perform different operations, and the main information passed by the server is still the new modulehashThe following steps are based on thishashValue to perform module hot replacement.
  5. webpack-dev-server/client The end does not request updates to the code, nor does it perform hot update module operations, and the work is still handed backwebpack.webpack/hot/dev-serverThe work is based onwebpack-dev-server/clientThe messages that were sent to it anddev-serverDetermines whether to refresh the browser or hot update the module. If you just refresh the browser, there is no further action.
  6. HotModuleReplacement.runtimeIs the clientHMRReceives the new module that was passed to it in the previous stephashValue, throughJsonpMainTemplate.runtimeserversendAjaxRequest, and the server returns onejsonthejsonContains all modules to be updatedhashValue, after getting the updated list, the module passes againjsonpRequest the latest module code.
  7. HotModulePluginThe old and new modules will be compared to decide whether to update the modules. After deciding to update the modules, the dependency relationship between the modules will be checked and the dependency references between the modules will be updated at the same time.
  8. whenHMRAfter failure, fall back tolive reloadAction, that is, a browser refresh to get the latest packaging code.

webpackOptimize front-end performance

  • Compressed code: Remove unnecessary code, comments, and simplified code writing. You can useUglifyJsPluginParallelUglifyPluginTo compress JS files, usingcssnanoTo compress CSS code.
  • CDN acceleration: During the construction process, the referenced static resource path is modified to the corresponding path on the CDN, which can be usedwebpackforoutputParameters and eachloader 的 publicPathParameter to modify the resource path.
  • Tree Shaking: To remove code fragments that will never go to the bootwebpackAppend parameter when--optimize-minimizeTo implement.
  • Code Splitting: Blocks code into routing dimensions or components that can be loaded on demand while taking full advantage of the browser cache.
  • Extract public third-party libraries:SplitChunksPluginPlug-ins for common module extraction, using the browser cache to cache this common code for a long time without frequent changes.

To improvewebpackPacking speed of

  • happypack: Uses process parallel compilationloader, using the cache to makerebuildFaster, similar alternatives:thread-loader.
  • External extensions: Detaching less needed third-party librarieswebpackPack to reduce packing time.
  • dll: in this paper,webpackDllPluginDllReferencePluginThe introduction ofdll, let some basic will not change the code first packaged into static resources, to avoid repeated compilation waste time.
  • Make use of caching:webpack.cache,babel-loader.cacheDirectory,HappyPack.cacheCan be improved by cachingrebuildThe time.
  • Narrow your file search: for examplebabel-loaderIf the file only exists insrcCan be used in:include: path.resolve(__dirname, src)

To improvewebpackConstruction speed of

  • Use in multiple entry casesCommonsChunkPluginTo extract common code
  • throughexternalConfigure to extract common libraries
  • usingDllPluginDllReferencePluginPrecompiled resource module, passDllPluginTo reference but never modifynpmPackage to precompile, and then passDllReferencePluginAdd and load the precompiled module
  • useHappyPackAchieve multithreaded accelerated compilation
  • usewebpack-uglify-parallelTo improveuglifyPluginCompression speed of
  • useTree-shakingScope HoistingTo weed out excess code