Vue series ten: webpack use

10.1. What is Webpack

Essentially, webpack is a static module bundler for modern JavaScript applications. When webpack processes an application, it recursively builds a dependency graph that contains every module the application needs, and then bundles all those modules into one or more bundles.
  Webpack is the hottest thing right now Front-end resource modular management and packaging tool, which can package many loosely coupled modules into front-end resources that meet production environment deployment according to dependencies and rules. You can also code-separate modules loaded on demand and load them asynchronously when they are actually needed. Through loader conversion, any form of resources can be used as modules, such as Commons JS, AMD, ES 6, CSS, JSON, Coffee Script, LESS, etc.
  With the tide of the mobile Internet, more and more websites today have changed from web mode Evolved to WebApp mode. They run in modern browsers and use new technologies such as HTML 5, CSS 3, ES 6 to develop rich functions. Web pages are not only the basic requirements of browsers; WebApp is usually a SPA (Single Page Application), Each view is loaded asynchronously, which leads to more and more JS code being loaded during page initialization and usage, which brings great challenges to the front-end development process and resource organization.
  The main difference between front-end development and other development work is that the front-end is based on multi-language, multi-level coding and organization work, and secondly, the delivery of front-end products is based on browsers, and these resources are run to the browser through incremental loading. , How to organize these fragmented codes and resources in the development environment, and ensure that they are loaded and updated quickly and gracefully on the browser side, requires a modular system. This ideal modular system is what front-end engineers have been working on for many years. Explore the puzzle.

10.2. Modular evolution

Script tag

	<script src = "module1.js"></script>
	<script src = "module2.js"></script>
	<script src = "module3.js"></script>

This is the most primitive way of loading JavaScript files. If each file is regarded as a module, then their interfaces are usually exposed in the global scope, that is, defined in the window object, and the invocation of different modules is a function. area.
  This primitive loading method exposes some obvious drawbacks:

  • It is easy to cause variable conflicts in the global scope
  • Files can only <script>be loaded in the order in which they are written
  • Developers have to resolve module and codebase dependencies subjectively
  • Various resources are difficult to manage in large-scale projects, and the long-term accumulation of problems leads to chaos in the code base

CommonsJS


NodeJS on the server side follows the CommonsJS specification. The core idea of ​​this specification is to allow modules to synchronously load other modules they need to depend on through the require method, and then export the interfaces that need to be exposed through exports or module.exports.

require("module");
require("../module.js");
export.doStuff = function(){};
module.exports = someValue;
1234

advantage:

  • Server-side modules for easy reuse
  • There are already over 450,000 packages available in NPM
  • Simple to use

shortcoming:

  • The synchronous module loading method is not suitable for the browser environment. Synchronous means blocking loading, and browser resources are loaded asynchronously.
  • Cannot load multiple modules in parallel without blocking

accomplish:

  • Server-side NodeJS
  • •Browserify, the implementation of CommonsJS on the browser side, can use NPM modules, but the compiled and packaged files are larger in size
  • modules-webmake, similar to Browserify, but not as flexible as Browserify
  • wreq, the predecessor of Browserify

AMD


The Asynchronous Module Definition specification actually has a main interface define(id?,dependencies?,factory); it specifies all dependencies when declaring the module, and also passes it to the factory as a formal parameter, and executes the dependent modules in advance .

define("module",["dep1","dep2"],functian(d1,d2){
	return someExportedValue;
});
require(["module","../file.js"],function(module,file){});
1234

advantage

  • Suitable for loading modules asynchronously in a browser environment
  • Multiple modules can be loaded in parallel

shortcoming

  • The development cost is increased, the code is difficult to read and write, and the semantics of the module definition method are not smooth
  • Does not fit the general modular mindset and is a compromise implementation

accomplish

  • RequireJS
  • curl

CMD


The Commons Module Definition specification is very similar to AMD, but keeps it simple and maintains great compatibility with the CommonsJS and NodeJS Modules specifications.

define(function(require,exports,module){
	var $=require("jquery");
	var Spinning = require("./spinning");
	exports.doSomething = ...;
	module.exports=...;
});

advantage:

  • Dependency is nearby, delayed execution
  • Can be easily run in NodeJS Cons
  • Depends on SPM packaging, and the loading logic of the module is heavy

accomplish

  • Sea.js
  • coolie

ES6 modules


The EcmaScript 6 standard adds a module system definition at the JavaScript language level. The design idea of ​​ES 6 modules is to be as static as possible, so that the dependencies of the modules and the variables of input and output can be determined at compile time. Commons JS and AMD modules, both can only determine these things at runtime.

import "jquery"
export function doStuff(){}
module "localModule"{}

advantage

  • Easy static analysis
  • Future-proof Ecma Script standard

shortcoming

  • Native browsers have not yet implemented this standard
  • Brand new commands, only supported by the new version of Node JS

accomplish

  • Babel

The expected module
  system is compatible with a variety of module styles, and the existing code can be used as much as possible, not only JavaScript modularization, but also CSS, images, fonts and other resources need to be modularized.

10.3. Install Webpack

WebPack is a module loader and packaging tool that can process and use various resources, such as JS, JSX, ES 6, SASS, LESS, pictures, etc., as modules.
  Install:

npm install webpack -g
npm install webpack-cli -g

Test installation was successful

  • webpack -v
  • webpack-cli -v

 

configure

Create webpack.config.jsconfiguration file

  • entry: entry file, specifying which file Web Pack uses as the entry for the project
  • output: output, specify WebPack to place the processed files in the specified path
  • module: module, used to process various types of files
  • plugins: plugins, such as: hot update, code reuse, etc.
  • resolve: set the path to point to
  • watch: monitoring, used to set the package directly after the file is changed
module.exports = {
	entry:"",
	output:{
		path:"",
		filename:""
	},
	module:{
		loaders:[
			{test:/\.js$/,;\loade:""}
		]
	},
	plugins:{},
	resolve:{},
	watch:true
}

Run webpackthe command directly to package

10.4. Using webpack

  1. Create project
  2. Create a directory called modules to place resource files such as JS modules
  3. Create a module file under modules, such as hello.js, for writing JS module related code
	//暴露一个方法:sayHi
	exports.sayHi = function(){
		document.write("<div>Hello Webpack</div>");
	}
  1. Create an entry file named main.js under modules to set the entry attribute when packaging
//require 导入一个模块,就可以调用这个模块中的方法了
var hello = require("./hello");
hello.sayHi();
  1. Create the webpack.config.js configuration file in the project directory and use the webpack command to package
module.exports = {
	entry:"./modules/main.js",
	output:{
		filename:"./js/bundle.js"
	}

}
  1. Create an HTML page in the project directory, such as index.html, and import the JS file packaged by webpack
	<!doctype html>
	<html lang="en">
		<head>
			<meta charset="UTF-8">
			<title>狂神说Java</title>
		</head>
		<body>
			<script src="dist/js/bundle.js"></script>
		</body>
	</html>
  1. Execute webpack directly in the IDEA console; if it fails, just run it with administrator privileges!
  2. Run HTML to see the effect

illustrate

# 参数--watch 用于监听变化
webpack --watch

Guess you like

Origin blog.csdn.net/qq_21137441/article/details/123768297