Master the construction tools Grunt, gulp, webpack in one day (below)

1. Gulp articles

Chinese homepage: http://www.gulpjs.com.cn/

In the above blog, we have described how to create a project and install all the environments and preparations. If you don't see it, the link is below

https://my.oschina.net/mdxlcj/blog/1626534

 

Next, our gulp tool also compresses and merges to test it.

* Create a simple application, directory structure
  ```
  |- dist
  |- src
    |- js
    |- css
    |- less
  |- index.html
  |- gulpfile.js-----gulp configuration file
  |- package.json
    {
      "name": "gulp_test",
      "version": "1.0.0"
    } 

as the picture shows

Then we write two js files mdx1.js and mdx2.js

Then right-click to create gulpfile.js, which is a special identification of the gulp tool

Then operate the script line command in Terminal

 Global installation of gulp: npm install gulp -g
  Local installation of gulp: npm install gulp --save-dev
 Configuration code: gulpfile.js
    //Introduce the gulp module
    var gulp = require('gulp');
    //Define the default task
    gulp.task ('task name', function() {
      // put your task's task code here
    });
    gulp.task('default', ['task'])//execute asynchronously

 

* Use gulp plugin
  * Related plugins:
    * gulp-concat : merge files (js/css)
    * gulp-uglify : compress js files
    * gulp-rename : rename files
    * gulp-less : compile less
    * gulp-clean-css : Compress css
    * gulp-livereload : Real-time automatic compilation refresh
  * Important API
    * gulp.src(filePath/pathArr) : 
      * All files pointed to the specified path, return file stream object
      * Used to read files
    * gulp.dest(dirPath/pathArr )
      * points to all the specified folders
      * is used to output files to the folder
    * gulp.task(name, [deps], fn) 
      * defines a task
    * gulp.watch() 
      * monitors file changes

 

The two folders we just created, mdx1.js and mdx2.js

(
    function () {
        function add(num1, num2) {
            return num1 + num2;
        }
        console.log(add(10, 20));
    }
)();

The two js are almost the same

 * Download plugin:
      npm install gulp-concat gulp-uglify gulp-rename --save-dev
    * Configure encoding
 
      var concat = require('gulp-concat');
      var uglify = require('gulp-uglify');
      var rename = require('gulp-rename');
      
      gulp.task('minifyjs', function() {
          return gulp.src('src/js/*.js') //The source file of the
              operation.pipe(concat('built. js')) //Merge to temporary     
              file.pipe(gulp.dest('dist/js')) //Generate to destination
              folder.pipe(rename({suffix: '.min'})) //Rename  
              .pipe(uglify())
              //Compression.pipe(gulp.dest('dist/js'));
      });
      
      gulp.task('default', ['minifyjs']);

That's about it. Maybe this one is very rubbish. After reading the previous one, you should understand the previous one and this one should be about the same.

2、Webpack

###1, understand Webpack related
    * What is webpack
        * Webpack is a module bundler (bundler).
        * In Webpack's view, all resource files (js/json/css/img/less/...) in the front end will be processed as modules
        * It will perform static analysis based on module dependencies and generate corresponding static resources
      * Understand Loader
        * Webpack itself can only load JS/JSON modules, if you want to load other types of files (modules), you need to use the corresponding loader for conversion/loading
        * Loader itself is also a JavaScript module running in the node.js environment
        * It itself is A function that accepts a source file as a parameter and returns the result of conversion
        * loader is generally named in the way of xxx-loader, where xxx represents the conversion function to be performed by this loader, such as json-loader.
      * Configuration file (default)
        * webpack.config.js : is a node module that returns a configuration information object in json format
    * Plug-ins
        * Plug-ins can perform some functions that loader cannot.
        * The use of plugins is generally specified in the plugins option of webpack's configuration information.
        * CleanWebpackPlugin: Automatically clear the specified folder resources
        * HtmlWebpackPlugin: Automatically generate HTML files and
        * UglifyJSPlugin: Compress js files
    
###2, learning documents: 
  * webpack official website: http://webpack.github.io/
  * webpack2 documentation (English): https://webpack.js .org/
  * webpack2 documentation (Chinese): https://doc.webpack-china.org/
###3. Open the project
  * Initialize the project:
      * Generate the package.json file
      * 
      ```   
      {
        "name": "webpack_test ",
        "version": "1.0.0"
      } 
      ```
  * Install webpack
    - npm install webpack -g //Global installation
    - npm install webpack --save-dev //Local installation
###4, compile and package applications
  * Create entry src/js/ : entry.js
    - document.write("entry.js is work");
  * Create main page: dist/index.html
    - <script type="text/javascript" src="bundle.js"></script>
  * Compile js
    - webpack src/js/entry.js dist/bundle.js  
  * View page effect
###5, add js/json file
    * Create a second js: src/js/math.js
        ``` 
        export function square(x) {
          return x * x;
        }
        
        export function cube(x) {
          return x * x * x;
        }
        ```
    * create json file: src/json/data.json
        ```
        {
          "name": "Tom",
          "age": 12
        }
        ```
    * update entry js : entry .js
        ```
        import {cube} from './math'
        import data from '../json/data.json'
        //Note that data will be automatically converted to a native js object or array
        document.write("entry.js is work <br />");
        document.write(cube(2) + '<br/>');
        document.write(JSON.stringify(data) + '<br/>')
        ```
    * Compile js:
        ```
        webpack src/js/entry.js dist/bundle.js
        ```
    * View page effect
###6. Use webpack configuration file
    * Create webpack.config.js
        ```
        const path = require('path'); / The /path built-in module is used to set the path.
        
        module.exports = {
          entry: './src/js/entry.js',

        ````     * Package application         ```         npm run build         ``` ###7, package css and image files    * install style loader     ```     npm install css-loader style-loader --save-dev     npm install file- loader url-loader --save-dev     Supplement: url-loader is the upper encapsulation of the object file-loader, and it needs to be used in conjunction with file-loader.     ````   * Configuration loader     ````























    module: {
      rules: [
        {
          test: /\.css$/,
          use: [
            'style-loader',
            'css-loader'
          ]
        },
        {
          test: /\.(png|jpg|gif)$/,
          use : [
            {
              loader: 'url-loader',
              options: {
                limit: 8192      
              }
            }
          ]
        }
      ]
    }
    ```
  * Add 2 images to the app:
    * Small image: img/logo.png
    * Large image: img/ big.jpg
    
  * create style file: src/css/test.css
    ```
    body {
      background: url('../img/logo.jpg')
    }
    ```
  * Update entry js : entry.js
    - import '../css/test.css'
  * Add css style

         #box1{
          width: 300px;
          height: 300px;
          background-image: url("../image/logo.jpg");
        }
        #box2{
          width: 300px;
          height: 300px;
          background-image: url("../image/big.jpg");
        }

  * index.html add the element
  
        <div id="box1"></div>
        <div id="box2"></div>
    
  * execute the package command:
    ```
    npm run build
    ```
  * found the problem:
      * large The image cannot be packaged into the entry.js file, and index.html is not in the generated resource directory.
      * The page loading image will be searched in the directory where it is located, so the large image path cannot be found when the page loads the image.
      * Solution:
          * Use publicPath: 'dist/js/' //Set the path to provide resources for index.html, after setting Find all resources will go to the current directory to find.
          * Putting index.html in dist/js/ can also solve it.
###8, Automatic compilation and packaging
    * Use webpack to develop server tools: webpack-dev-server
    * Download
        - npm install --save-dev webpack-dev-server
    * webpack configuration
          devServer: {
            contentBase: './dist'

    * package configuration
        - "start": "webpack-dev-server --open"
    * Compile and package the application and run
        - npm start
###9, use webpack plug-ins
  * commonly used plug-ins
    * use html-webpack-plugin to generate based on template html Pages that import scripts
    * Use clean-webpack-plugin to clear the dist folder
    * Use uglifyjs-webpack-plugin to compress the packaged js files
  * Download
    ```
    npm install --save-dev html-webpack-plugin clean-webpack-plugin
    ` ``
  * webpack-config

        const HtmlWebpackPlugin = require('html-webpack-plugin'); //A plugin that automatically generates html files
        const CleanWebpackPlugin = require('clean-webpack-plugin'); //Clear the previously packaged files   
        plugins: [
          new HtmlWebpackPlugin({ template: './index.html'}),
          new CleanWebpackPlugin(['dist']),
        ]

  * Create page: index.html

        <!DOCTYPE html>
        <html lang="en">
        <head>
          <meta charset="UTF-8">
          <title>webpack test</title>
        </head>
        <body>
        <div id="app"> </div>
        <!--The packaged file will be automatically injected here through the script tag-->
        </body>
        </html>

  * Package and run the project
    ```
    npm run build
    npm start

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324995058&siteId=291194637