What are the common static resource references in a Web page?
- JS
- .js .jsx .coffee .ts (TypeScript class C # language)
- CSS
- .css .less .sass .scss
- Images
- .jpg .png .gif .bmp .svg
- Font file (Fonts)
- .svg .ttf .eot .woff .woff2
- Template files
- .ejs .jade .vue [This is the way webpack defined components, such use is recommended]
Static resource page introduced much later what is the problem? ? ?
- Slow loading pages, because we want to launch a lot of secondary request;
- To deal with complex dependencies
How to solve these two problems
- Consolidation, compression, sprite, Base64 encoded image
- Learned previously may be used requireJS, may also be used webpack solve complex dependencies between individual packets;
First, what is webpack?
webpack is a front-end project build tool, which is based on Node.js developed a front-end tool;
How perfect realization of the above two kinds of solutions
- Use Gulp, it is based on the task task;
- Use Webpack, based on the entire project is built;
- Build automation tools by means of webpack the front end, you can achieve the perfect merger of resources, packing, compression, confusion, and many other functions.
- Describes the process webpack packaged according to the official website of the picture
- webpack official website
webpack installed in two ways
- Run
npm i webpack -g
a global installation webpack, so you can use commands in the global webpack - In the project root directory, run
npm i webpack --save-dev
the installation to the project dependencies
Preliminary packaged using webpack build a list of interlaced color Case
-
Run
npm init
initialize the project, using npm manage project dependenciesThis process is in the current directory (E: \ Workspace \ my-npm-project) package.json create a name for the file and write the following information
name:包名 version:版本,第一个数字一般为版本不兼容改动,第二个数字为版本兼容的功能修改,第三个为版本兼容的bug修复 description:包的说明 main:入口文件 scripts:可执行的脚本命令 keywords:关键字 author:作者 license:许可证书
-
Creating a basic project directory structure
在项目根目录下创建src文件夹和index.js文件。 src存放源文件;index.js为包入口。
-
Use
cnpm i jquery --save
installation jquery library -
Create
main.js
and write each line discoloration code logic:// 导入jquery类库 import $ from 'jquery' // 设置偶数行背景色,索引从0开始,0是偶数 $('#list li:even').css('backgroundColor','lightblue'); // 设置奇数行背景色 $('#list li:odd').css('backgroundColor','pink');
-
References directly on the page html
main.js
will complain because the browser does not recognizeimport
such a high level of JS grammar, use webpack processing, webpack default this will be converted to low-level syntax browser can recognize grammar;<!-- 因为 main 中的代码,涉及到了ES6的新语法,但是浏览器不识别 --> <!-- <script src="./main.js"></script> -->
-
Run
webpack 入口文件路径 输出文件路径
tomain.js
the following conditions:webpack src/js/main.js dist/bundle.js
<!-- 通过 webpack 这么一个前端构建工具, 把 main.js 做了一下处理,生成了一个 bundle.js 的文件 --> <!-- <script src="../dist/bundle.js"></script> -->
After just a demo, Webpack can do anything? ? ?
1. webpack 能够处理 JS 文件的互相依赖关系; 2. webpack 能够处理JS的兼容问题,把 高级的、浏览器不识别的语法,转为 低级的,浏览器能正常识别的语法 刚才运行的命令格式:webpack 要打包的文件的路径 打包好的输出文件的路径
Second, the use of simplified profile WebPACK packaged command time (webpack: inlet and outlet do not manually specified file, automatic)
-
Created in the project root directory
webpack.config.js
-
Since time is running webpack command, webpack you need to specify the path to the entrance and output files, so we need
webpack.config.js
to configure the two paths: -
Node.js in, __ dirname absolute path is always executed js file, so when you write __dirname in /d1/d2/myscript.js file, its value is / d1 / d2.
// 导入处理路径的模块 var path = require('path'); // 导出一个配置对象,将来webpack在启动的时候,会默认来查找webpack.config.js,并读取这个文件中导出的配置对象,来进行打包处理 module.exports = { entry: path.resolve(__dirname, 'src/js/main.js'), // 项目入口文件 output: { // 配置输出选项 path: path.resolve(__dirname, 'dist'), // 配置输出的路径 filename: 'bundle.js' // 配置输出的文件名 } }
Third, to achieve real-time package webpack Construction (webpack-dev-server)
Webpack-dev-server use this tool to automatically package compiled function
- Run npm i webpack-dev-server -D install this tool to local development projects dependent
- After installation, the use of this tool, and usage webpack commands, exactly the same
- Since we are in the project, locally installed webpack-dev-server, therefore, you can not treat it as a script commands, run powershell directly in the terminal; (only those attached to the tool of the global -g, to function properly in the terminal carried out)
- Note: webpack-dev-server tool, if you want to normal operation, requiring, in the local project, you must install webpack
- webpack-dev-server package to help us generate the bundle.js file, and not to the actual physical storage disk; rather, hosted directly to the computer's memory, so we in the project root directory, could not find this packaged bundle.js;
- We can think, webpack-dev-server to packaged file, in a form of virtual hosting to the root of our project, although we can not see it, however, it is believed, and dist src node_modules same level, there is an invisible file called bundle.js
Highlights:
- Because after each re-modify the code, you need to manually run webpack packaged command, too much trouble, so use
webpack-dev-server
to compile code that implements real-time package, when modifying the code, it will automatically build packages. - Run
cnpm i webpack-dev-server --save-dev
the installation to the development of dependence - After the installation is complete, run directly from the command line
webpack-dev-server
to package and found an error, this time by means of the requiredpackage.json
file command to run thewebpack-dev-server
command in thescripts
new node under"dev": "webpack-dev-server"
instructions, can be found packaged real-time, but not under the dist directory generate abundle.js
file, this is becausewebpack-dev-server
the packaged file in the memory
-
Put
bundle.js
in memory of the benefits are: real-time package due to the need to compile, so in memory speed will be very fast -
This time access webpack-dev-server start
http://localhost:8080/
site, the panel found a folder, you need to click on the src directory, to open our index page, this time less than bundle.js reference file, you need to modify the index.html script src attribute as follows:<script src="../bundle.js"></script>
-
To be able to access
http://localhost:8080/
direct access to the index of home when you can use--contentBase src
commands to modify dev command, specify the start of the root directory:"dev": "webpack-dev-server --contentBase src"
At the same time modify the src attribute index page script is
<script src="bundle.js"></script>
The use of html-webpack-plugin
plug-in configuration startup page (two functions)
Due to the use of --contentBase
the instruction process more complicated, you need to specify the directory to start, but also need to modify the src attribute of the script tag in index.html, so we recommend using a html-webpack-plugin
plug-in configuration startup page.
-
Run
cnpm i html-webpack-plugin --save-dev
the installation to the development of dependence -
Modify
webpack.config.js
the configuration file as follows:/ * Import Plug-generated HTML pages in memory as long as the plug-in, all the nodes must be placed plugins to
the plugin's two roles:- Automatically generating a page memory based on the specified page in the memory
- Automatically appended to the packaged bundle.js to page
* /
// Import module processing path
var path = the require ( 'path');
// import file automatically generated HTMl plug
var htmlWebpackPlugin = require ( 'html- webpack-plugin ');
----------------------------- module.exports = { plugins:[ // 添加plugins节点配置插件 new htmlWebpackPlugin({ template:path.resolve(__dirname, 'src/index.html'),//模板路径 filename:'index.html'//自动生成的HTML文件的名称 }) ] }
-
Modifying
package.json
thescript
node dev instructions are as follows:"dev": "webpack-dev-server"
-
The script tag in index.html commented, because
html-webpack-plugin
plugin will automatically bundle.js injected into the index.html page!
Fifth, the browser automatically open the default port number for the hot update and configure your browser
Note: hot update is not obvious in the performance of JS can be introduced from moment to explain who mentioned CSS!
Mode 1:
-
Modify
package.json
the script node below which--open
represents the browser automatically opens,--port 4321
represents an open port number 4321,--hot
indicate enabled browser hot update:"dev": "webpack-dev-server --hot --port 4321 --open"
Option 2:
-
Modify the
webpack.config.js
file, adddevServer
nodes as follows:devServer:{ hot:true, open:true, port:4321 }
-
Introducing the head
webpack
module:var webpack = require('webpack');
-
In the
plugins
next node is added:new webpack.HotModuleReplacementPlugin()
Sixth, the use webpack package css file
-
run
cnpm i style-loader css-loader --save-dev
-
Modify
webpack.config.js
the configuration file:// 用来配置第三方loader模块的 module: { // 文件的匹配规则 rules: [ //处理css文件的规则 { test: /\.css$/, use: ['style-loader', 'css-loader'] } ] }
-
Note:
use
indicates which modules are used to processtest
the matched file;use
sequence of calls related to the loader module is called from the front;
Seven, the use of less packaging webpack file
-
run
cnpm i less-loader less -D
-
Modify
webpack.config.js
the configuration file:{ test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader'] },
Eight, the use webpack packaged sass file
-
run
cnpm i sass-loader node-sass --save-dev
-
In
webpack.config.js
addition processing sass file loader module:{ test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'] }
IX using the url path webpack process in css
By default, webpack can not handle CSS file url address, whether it is pictures or font library, as long as the URL, you can not deal with
-
run
cnpm i url-loader file-loader --save-dev
-
In
webpack.config.js
addition processing path loader module url:{ test: /\.(png|jpg|gif)$/, use: 'url-loader' }
-
By
limit
image sizes specified base64 encoded; just less than the specified byte (byte) will be base64 encoded images:{ test: /\.(png|jpg|gif)$/, use: 'url-loader?limit=43960&name=[hash:8]-[name].[ext]' }
-
Processing font file (fonts) of the loader
{ test: /\.(ttf|eot|svg|woff|woff2)$/, use: 'url-loader' }
Ten advanced processing using babel JS syntax (babel is js compiler)
In webpack, the default can only deal with part of the new syntax for ES6, ES6 some more advanced grammar or syntax ES7, webpack is not treated;
At this time, we need the help of third-party loader, webpack to help deal with these advanced grammar,
When a third-party loader to low-level syntax into the syntax, the result will go to the webpack packaged in bundle.js.
By loader: Babel, can help us to convert low-level syntax of grammar.
(1) In webpack you can run the following command sets, two sets of packages, to install the loader Babel related functions:
- Running
cnpm i babel-core babel-loader babel-plugin-transform-runtime --save-dev
the installation package babel relevant loader ** (converter) ** - Run
cnpm i babel-preset-es2015 babel-preset-stage-0 --save-dev
the installation babel The syntax ** (syntax conversion) **
(2) Open webpack profile, the array of rules in the module node, adding a new mapping rules:
-
In
webpack.config.js
adding the relevant module loader, which should be noted is that we must putnode_modules
the folder (inside the js) to add exclusions:{ test: /\.js$/, use: 'babel-loader', exclude: /node_modules/ }
-
Add in the project root directory
.babelrc
file and modify the configuration file as follows:Configure Plug-babel
JSON syntax must conform to specifications: You can not write comments, strings must be enclosed in double quotes
{ "presets":["es2015", "stage-0"], "plugins":["transform-runtime"] }
-
Note: The syntax plugin
babel-preset-es2015
can be updatedbabel-preset-env
, it contains all the syntax of ES-related;