vue in use Webpack

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? ? ?

  1. Slow loading pages, because we want to launch a lot of secondary request;
  2. To deal with complex dependencies

How to solve these two problems

  1. Consolidation, compression, sprite, Base64 encoded image
  2. 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

  1. Use Gulp, it is based on the task task;
  2. 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

  1. Run npm i webpack -ga global installation webpack, so you can use commands in the global webpack
  2. In the project root directory, run npm i webpack --save-devthe installation to the project dependencies

Preliminary packaged using webpack build a list of interlaced color Case

  1. Run npm initinitialize the project, using npm manage project dependencies

    This 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:许可证书
    
  2. Creating a basic project directory structure

     	在项目根目录下创建src文件夹和index.js文件。
     	src存放源文件;index.js为包入口。
    
  3. Use cnpm i jquery --saveinstallation jquery library

  4. Create main.jsand write each line discoloration code logic:

    		// 导入jquery类库
    	    import $ from 'jquery'
    	   
    	    // 设置偶数行背景色,索引从0开始,0是偶数
    	    $('#list li:even').css('backgroundColor','lightblue');
    	    // 设置奇数行背景色
    	    $('#list li:odd').css('backgroundColor','pink');
    
  5. References directly on the page html main.jswill complain because the browser does not recognize importsuch 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> -->
    
  6. Run webpack 入口文件路径 输出文件路径to main.jsthe 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)

  1. Created in the project root directorywebpack.config.js

  2. Since time is running webpack command, webpack you need to specify the path to the entrance and output files, so we need webpack.config.jsto configure the two paths:

  3. 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

  1. Run npm i webpack-dev-server -D install this tool to local development projects dependent
  2. After installation, the use of this tool, and usage webpack commands, exactly the same
  3. 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)
  4. Note: webpack-dev-server tool, if you want to normal operation, requiring, in the local project, you must install webpack
  5. 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;
  6. 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:

  1. Because after each re-modify the code, you need to manually run webpack packaged command, too much trouble, so use webpack-dev-serverto compile code that implements real-time package, when modifying the code, it will automatically build packages.
  2. Run cnpm i webpack-dev-server --save-devthe installation to the development of dependence
  3. After the installation is complete, run directly from the command line webpack-dev-serverto package and found an error, this time by means of the required package.jsonfile command to run the webpack-dev-servercommand in the scriptsnew node under "dev": "webpack-dev-server"instructions, can be found packaged real-time, but not under the dist directory generate a bundle.jsfile, this is because webpack-dev-serverthe packaged file in the memory
  • Put bundle.jsin 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 srccommands 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-pluginplug-in configuration startup page (two functions)

Due to the use of --contentBasethe 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-pluginplug-in configuration startup page.

  1. Run cnpm i html-webpack-plugin --save-devthe installation to the development of dependence

  2. Modify webpack.config.jsthe 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:

    1. Automatically generating a page memory based on the specified page in the memory
    2. 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文件的名称
                 })
             ]
         }
    
  3. Modifying package.jsonthe scriptnode dev instructions are as follows:

     "dev": "webpack-dev-server"
    
  4. The script tag in index.html commented, because html-webpack-pluginplugin 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.jsonthe script node below which --openrepresents the browser automatically opens, --port 4321represents an open port number 4321, --hotindicate enabled browser hot update:

      "dev": "webpack-dev-server --hot --port 4321 --open"
    

Option 2:

  1. Modify the webpack.config.jsfile, add devServernodes as follows:

     devServer:{
             hot:true,
             open:true,
             port:4321
         }
    
  2. Introducing the head webpackmodule:

     var webpack = require('webpack');
    
  3. In the pluginsnext node is added:

     new webpack.HotModuleReplacementPlugin()
    

Sixth, the use webpack package css file

  1. runcnpm i style-loader css-loader --save-dev

  2. Modify webpack.config.jsthe configuration file:

     // 用来配置第三方loader模块的
     module: { 
     		// 文件的匹配规则
             rules: [ 
     			//处理css文件的规则
                 { test: /\.css$/, use: ['style-loader', 'css-loader'] }
             ]
         }
    
  3. Note: useindicates which modules are used to process testthe matched file; usesequence of calls related to the loader module is called from the front;

Seven, the use of less packaging webpack file

  1. runcnpm i less-loader less -D

  2. Modify webpack.config.jsthe configuration file:

     { test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader'] },
    

Eight, the use webpack packaged sass file

  1. runcnpm i sass-loader node-sass --save-dev

  2. In webpack.config.jsaddition 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

  1. runcnpm i url-loader file-loader --save-dev

  2. In webpack.config.jsaddition processing path loader module url:

     { test: /\.(png|jpg|gif)$/, use: 'url-loader' }
    
  3. By limitimage 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]' }
    
  4. 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:

  1. Running cnpm i babel-core babel-loader babel-plugin-transform-runtime --save-devthe installation package babel relevant loader ** (converter) **
  2. Run cnpm i babel-preset-es2015 babel-preset-stage-0 --save-devthe installation babel The syntax ** (syntax conversion) **

(2) Open webpack profile, the array of rules in the module node, adding a new mapping rules:

  1. In webpack.config.jsadding the relevant module loader, which should be noted is that we must put node_modulesthe folder (inside the js) to add exclusions:

     { test: /\.js$/, use: 'babel-loader', exclude: /node_modules/ }
    
  2. Add in the project root directory .babelrcfile 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"]
     }
    
  3. Note: The syntax plugin babel-preset-es2015can be updated babel-preset-env, it contains all the syntax of ES-related;

Guess you like

Origin blog.csdn.net/lidongliangzhicai/article/details/93027211