Getting Started Webpack

Source: Internet
Author: User
Tags bind hash html page require
What is Webpack

Webpack is a static module wrapper for a modern JavaScript application (modules bundler). When Webpack processes an application, it constructs a dependency graph (dependency graph) recursively, which contains each module that the application requires, and then packages all of them into one or more bundles.

It is highly configurable, but before you begin you need to understand the four core concepts: the ingress (entry) output (outputs)loader (loader) plug-in (plugins ) Unique Portal File entry

1. Single Entry (abbreviated) syntax
Usage: entry:string| Array<string>

Webpack.config.js

Const CONFIG = {
  entry: './path/to/my/entry/file.js '
};

module.exports = config;

Entry single entry syntax, is the following shorthand:

Const CONFIG = {
  entry: {
    main: './path/to/my/entry/file.js '
  }
};

2. Object Syntax
Usage: entry: {[entrychunkname:string]: string| Array<string>}

Webpack.config.js

Const CONFIG = {
  entry: {
    app: './src/app.js ',//Application
    Vendors: './src/vendors.js '//third-party library entry
  }
};

Object syntax can be tedious. However, this is the most extensible way to define portals in your application. Output Outputs

The minimum requirement to configure the output property in Webpack is to set its value to an object, including the following two points: filename for the output file. The absolute path of the target output directory path.

Webpack.config.js

Const CONFIG = {
  output: {
    filename: ' bundle.js ',
    path: '/home/proj/public/assets '
  }
};

module.exports = config;
This configuration outputs a separate bundle.js file to the/home/proj/public/assets directory.
//If the configuration creates multiple separate "chunk", placeholders should be used to ensure that each file has a unique name.

{
  entry: {
    app: './src/app.js ',
    search: './src/search.js '
  },
  output: {
    FileName: ' [name].js ',
    path: __dirname + '/dist '
  }
}

//write to Hard disk:./dist/app.js,./dist/search.js
Loader Loader

The loader is used to convert the module's source code. Loader allows you to preprocess files when you import or "load" the module. Loader provides additional capabilities for the JavaScript ecosystem through the (loader) preprocessing function. Users now have more flexibility to introduce fine-grained logic, such as compression, packaging, language translation, and more test: regular expressions, to match file names (must) Loader: The list of loaders to load, use! Load more than one (must) Include/exclude: Manually add files (folders) that must be processed (folder) or block files (folders) that you do not need to process (optional); query: Provide additional setup options for loaders (optional) use Loader

In your application, there are three ways to use loader: configuration (Recommended): Specify loader in the Webpack.config.js file.

Module: {  //loader
            rules: [{
                    test:/(\.jsx|\.js) $/, use
                    : {
                        loader: "Babel-loader"
                    },
                    Exclude:/node_modules/
                }
        ]
    },
Inline: explicitly specify loader in each import statement.
Import Styles from ' style-loader!css-loader?modules!. /styles.css ';
CLI: Specify them in the shell command.
Webpack--module-bind jade-loader--module-bind ' Css=style-loader!css-loader '
css,css preprocessing loading

Webpack provides two tools for working with style sheets Css-loader Style-loader The tasks they handle are different, Css-loader enables you to use similar @import and URLs (...) method to implement the Require () function, style-loader all the computed styles into the page, the combination of which allows you to embed the stylesheet into the Webpack packaged JS file.

Installing
npm Install--save-dev style-loader css-loader
Plugin Plugins

Since the plug-in can carry parameters/options , you must pass the new instance to the Plugins property in the webpack configuration. With built -in plug-ins and extensions

Mode one
const Htmlwebpackplugin = require (' Html-webpack-plugin ');//install
const WEBPACK = require (' Webpack ') via NPM ; Access the built-in plugin//

mode two (built-in), three (extension)
 plugin: [//plugin
    //built-in compression plug-in
    new Webpack.optimize.UglifyJsPlugin ({ Compressor: {Warnings:false,},}),
    //Extension
    Componentplugin ()
  ]
Resolve configuration file Other solutionsResolve is another solution configured, such as Resolve.alias can define the alias of a module, Resolve.root can define an absolute path. Resolve.extensions can save the suffix name of the loaded file, that is, the suffix is auto-complete. However, you must precede with an empty string, otherwise it will cause the situation to fail to load.
Resolve: {
    extensions: ['. js ', '. Vue ', '. JSON '],
    alias: {
      ' vue$ ': ' vue/dist/vue.esm.js ',
      ' @ ': Resolve (' src ')
    }
  },
Webpack-dev-server

Webpack-dev-server is a NODEJS server dedicated to Webpack, installed through the NPM install--save-dev webpack-dev-server command.

Devserver configuration Options Feature Description
Contentbase default Webpack-dev-server provides a local server for the root folder, and if you want to provide a local server for files in another directory, you should set up the directory where it is located (this example is set to the "public" directory)
Port sets the default listening port, if omitted, the default is "8080"
Inline is set to true to automatically refresh the page when the source file changes
Historyapifallback is useful when developing a single page application, it relies on the HTML5 history API, and if set to true, all jumps will point to index.html

Webpack.config.js
devserver: {
  contentbase: "./",//The  directory where the local server loads the page is
  colors:true,  // The output of the terminal is color
  historyapifallback:true,  //Do not jump inline:true//  real-time Refresh
}
Babel

Babel is a compiled JavaScript platform that is very powerful and can be compiled JSX,ES6,ES7 to generate the JavaScript language that the browser recognizes. Multiple dependencies need to be installed: NPM install--save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react.

Webpack.config.js
module: {
  loaders: [
    {
      test:/\.js$/,
      exclude:/node_modules/,
      Loader: ' Babel ',
      query: {
        presets: [' es2015 ', ' React '}
      }
  ]
},
Html-webpack-plugin

This plugin is mainly for HTML, can automatically generate HTML files, especially when the use of hash, do not bother because of the hash of the changes brought about by the problem.

var webpack = require (' Webpack ')
var htmlwebpackplugin = require (' Html-webpack-plugin ')
module.exports = {
  entry: './main.js ',
  output: {
    path: __dirname,
    filename: ' Bundle.js '
  },
  plugins: [New Htmlwebpackplugin ()]
}

Sometimes, because there must be something special in HTML that cannot be generated directly, you need to configure the template at this point:

Module.exports = {
  plugins:[
    new Htmlwebpackplugin ({
      filename: ' hello.html ',//generated file
      Template: ' Src/template.html '//template file
    }
  ]
}
Title: page Title filename: The output of the HTML file name, the default is index.html Template: Templates file path, support loader, such as html!. /index.html Inject:true | ' Head ' | ' Body ' | False, inject all the resources into a specific template or TemplateContent, if set to true or body, all JavaScript resources will be placed at the bottom of the BODY element, ' head ' will be placed in the head element 。 Favicon: Adds a specific favicon path to the output HTML file. Minify: {} | False, pass html-minifier option to minify output Hash:true | False, if true, adds a unique Webpack compilation hash to all included scripts and CSS files, which is useful for unlocking the cache. Cache:true | False, if true, this is the default value, and the file is published only after the file has been modified. Showerrors:true | False, if true, this is the default, and the error message is written to the HTML page chunks: Allow only some blocks (for example, only the unit test block) Chunkssortmode: Allows the control block to be sorted before it is added to the page, supported by the value: ' Non E ' | ' Default ' | {function}-default: ' auto ' excludechunks: Allow skipping of certain blocks (e.g., skipping blocks of unit tests)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.