search
HomeWeb Front-endJS TutorialDetailed introduction to webpack

Detailed introduction to webpack

Jun 26, 2017 am 09:08 AM
webwebpackstudyrookie

Webpack is a front-end tool that allows each module to be loaded, preprocessed, and packaged. It has all the basic functions of Grunt or Gulp.

I used gulp before to package and compress the css and js of the page. The configuration is simple, but it is too trivial and troublesome. When using sass, it is easy to import the sass file directly into sass. Error reported (I don’t know what happened)

What attracts me to webpack: modularization, on-demand loading, compressed css, inline styles, and independent styles. Compress js, compress page

Reference article: (1.0 version)

Learning video: (1.0 version)

Install webpack version 2.0 by yourself (some areas need attention)

1. Installation

Install test node and npm

1 $ node -v2 v6.11.0
$ npm -v3.10.10

Create a new folder webpack, enter the project directory webpack, and install it:

1, use npm init -y to generate the package.json file

npm init -y

2, install webpack (it seems to install webpack globally, you can directly enter webpack on the command line for packaging)

//全局安装
npm install -g webpack
//安装到你的项目目录
npm install --save-dev webpack

The test webpack version is: $ webpack -v 2.6.1

Configuration command

This is configured in the package.json file

"scripts": {"build": "webpack  --profile --progress --colors --display-error-details","dev": "webpack  --display-modules --profile --progress --colors --display-error-details","dev-hrm": "webpack-dev-server --config"
  },
  • color The output result is colored, for example: Longer-consuming steps will be displayed in red

  • profile output performance data, you can see the time-consuming of each step

  • progress output current The progress of compilation, presented in the form of percentage

  • display-modules By default, the modules under node_modules will be hidden, adding this parameter can display these hidden modules

  • display-error-details Output detailed error information

  • webpack-dev-server will enable hot update

  • For more information, please refer to the official website cli

##
// 开发模式npm run dev// 热更新模式npm run dev-hrm// 发布模式npm run build

2. Configuration

New webpack.config.js

module.exports = {
entry:{

main:"./src/app.js?1.1 .11",
 } ,
//The only entry file that has been mentioned many times

+ "/dist",filename: "js/[name].js?1.1.11",

HtmlWebpackPlugin

Based on a simple template, help you generate the final Html5 file

npm install --save-dev html-webpack-plugin

    plugins:[new htmlWebpackPlugin({
            filename:'index.html',
            template:'index.html',
            inject:'body',
            title:'首页',
        }),
    ]

Loaders

The famous Loaders are here!

Loaders are one of the most exciting features in webpack. By using different loaders, webpack can process files in various formats by calling external scripts or tools, such as analyzing JSON files and converting them into JavaScript files, or converting next-generation JS files (ES6 , ES7) into a JS file that modern browsers can recognize. In other words, for React development, appropriate Loaders can convert React's JSX files into JS files.

<br/>

Loaders need to be installed separately and configured under the

modules keyword under webpack.config.js. The configuration options of Loaders include the following aspects:

<br/>

  • test: A regular expression matching the extension of the file processed by loaders (required)

  • loader : The name of the loader (required)

  • include/exclude: Manually add files (folders) that must be processed or block files (folders) that do not need to be processed. (Optional);

  • query: Provide additional setting options for loaders (optional)

Babel

Babel is actually a platform for compiling JavaScript. Its power is that it can help you achieve the following goals through compilation:

<br/>

  • The next generation of JavaScript standards (ES6 , ES7), these standards are currently not fully supported by current browsers;

  • Use languages ​​based on JavaScript that have been expanded, such as React’s JSX

// npm一次性安装多个依赖模块,模块之间用空格隔开npm install --save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react

{
                test: /\.js$/,
                loader: 'babel-loader',
                include: path.resolve(__dirname,'src'),
                exclude: path.resolve(__dirname,'node_modules'),
                query:{
                    presets:["es2015"]
                }
             }
CSS, CSS preprocessor

First install postcss-loader and autoprefixer (plug-in that automatically adds prefixes )

npm install --save-dev style-loader css-loader
{
                 test:/\.css$/,
                 loader: [                  'style-loader',
                  { loader: 'css-loader', options: { importLoaders: 1 } },                  'postcss-loader']
             }
npm install --save-dev less-loader less
npm install --save-dev postcss-loader autoprefixer

 

 在完成一系列的操作后

 

package.json:

{  "name": "webpack",  "version": "1.0.0",  "main": "index.js?1.1.11",  "scripts": {"test": "echo \"Error: no test specified\" && exit 1","webpack": "webpack --config webpack.config.js --progress --display-module --colors"
  },  "keywords": [],  "author": "",  "license": "ISC",  "devDependencies": {"autoprefixer": "^7.1.1","babel-core": "^6.25.0","babel-loader": "^7.0.0","babel-preset-es2015": "^6.24.1","babel-preset-latest": "^6.24.1","babel-preset-react": "^6.24.1","css-loader": "^0.28.4","file-loader": "^0.11.2","html-loader": "^0.4.5","html-minify-loader": "^1.1.0","html-webpack-plugin": "^2.28.0","image-webpack-loader": "^3.3.1","less": "^2.7.2","less-loader": "^4.0.4","postcss-loader": "^2.0.5","style-loader": "^0.18.2","url-loader": "^0.5.9","webpack": "^2.6.1"
  },  "dependencies": {"acorn": "^5.0.3","acorn-dynamic-import": "^2.0.2","ajv": "^4.11.8","anymatch": "^1.3.0","align-text": "^0.1.4","arr-diff": "^2.0.0","arr-flatten": "^1.0.3","array-unique": "^0.2.1","arrify": "^1.0.1","asn1.js?1.1.11": "^4.9.1","async": "^2.4.1","async-each": "^1.0.1","balanced-match": "^1.0.0","base64-js": "^1.2.0","binary-extensions": "^1.8.0","bn.js?1.1.11": "^4.11.6","brace-expansion": "^1.1.8","braces": "^1.8.5","brorand": "^1.1.0","browserify-aes": "^1.0.6","browserify-cipher": "^1.0.0","browserify-des": "^1.0.0","browserify-sign": "^4.0.4","browserify-zlib": "^0.1.4","buffer": "^4.9.1","buffer-xor": "^1.0.3","builtin-modules": "^1.1.1","builtin-status-codes": "^3.0.0","camelcase": "^3.0.0","center-align": "^0.1.3","chokidar": "^1.7.0","cipher-base": "^1.0.3","co": "^4.6.0","cliui": "^3.2.0","browserify-rsa": "^4.0.1","code-point-at": "^1.1.0","assert": "^1.4.1","concat-map": "^0.0.1","console-browserify": "^1.1.0","constants-browserify": "^1.0.0","create-hmac": "^1.1.6","create-ecdh": "^4.0.0","crypto-browserify": "^3.11.0","create-hash": "^1.1.3","date-now": "^0.1.4","decamelize": "^1.2.0","des.js?1.1.11": "^1.0.0","diffie-hellman": "^5.0.2","domain-browser": "^1.1.7","elliptic": "^6.4.0","enhanced-resolve": "^3.1.0","errno": "^0.1.4","events": "^1.1.1","error-ex": "^1.3.1","expand-brackets": "^0.1.5","expand-range": "^1.8.2","extglob": "^0.3.2","filename-regex": "^2.0.1","fill-range": "^2.2.3","find-up": "^1.1.2","for-own": "^0.1.5","evp_bytestokey": "^1.0.0","get-caller-file": "^1.0.2","fsevents": "^1.1.1","glob-base": "^0.3.0","for-in": "^1.0.2","glob-parent": "^2.0.0","graceful-fs": "^4.1.11","has-flag": "^1.0.0","hash.js?1.1.11": "^1.0.3","hash-base": "^2.0.2","hmac-drbg": "^1.0.1","hosted-git-info": "^2.4.2","html-webpack-plugin": "^2.28.0","https-browserify": "^0.0.1","ieee754": "^1.1.8","ajv-keywords": "^1.5.1","indexof": "^0.0.1","invert-kv": "^1.0.0","interpret": "^1.0.3","is-arrayish": "^0.2.1","is-binary-path": "^1.0.1","is-buffer": "^1.1.5","is-dotfile": "^1.0.3","is-builtin-module": "^1.0.0","is-equal-shallow": "^0.1.3","is-extendable": "^0.1.1","is-extglob": "^1.0.0","is-fullwidth-code-point": "^1.0.0","is-glob": "^2.0.1","is-number": "^3.0.0","is-posix-bracket": "^0.1.1","is-primitive": "^2.0.0","is-utf8": "^0.2.1","json-loader": "^0.5.4","json-stable-stringify": "^1.0.1","jsonify": "^0.0.0","kind-of": "^4.0.0","isobject": "^2.1.0","lazy-cache": "^1.0.4","lcid": "^1.0.0","load-json-file": "^1.1.0","loader-runner": "^2.3.0","longest": "^1.0.1","micromatch": "^2.3.11","memory-fs": "^0.4.1","minimalistic-assert": "^1.0.0","miller-rabin": "^4.0.0","minimalistic-crypto-utils": "^1.0.1","minimatch": "^3.0.4","mkdirp": "^0.5.1","minimist": "^0.0.8","node-libs-browser": "^2.0.0","normalize-path": "^2.1.1","object.omit": "^2.0.1","number-is-nan": "^1.0.1","os-browserify": "^0.2.1","os-locale": "^1.4.0","normalize-package-data": "^2.3.8","pako": "^0.2.9","parse-asn1": "^5.1.0","parse-glob": "^3.0.4","parse-json": "^2.2.0","path-browserify": "^0.0.0","path-exists": "^2.1.0","path-type": "^1.1.0","pbkdf2": "^3.0.12","pify": "^2.3.0","path-is-absolute": "^1.0.1","pinkie": "^2.0.4","pinkie-promise": "^2.0.1","preserve": "^0.2.0","process": "^0.11.10","process-nextick-args": "^1.0.7","prr": "^0.0.0","public-encrypt": "^4.0.0","punycode": "^1.4.1","querystring": "^0.2.0","querystring-es3": "^0.2.1","randomatic": "^1.1.7","randombytes": "^2.0.5","read-pkg": "^1.1.0","read-pkg-up": "^1.0.1","readdirp": "^2.1.0","regex-cache": "^0.4.3","repeat-element": "^1.1.2","repeat-string": "^1.6.1","require-directory": "^2.1.1","right-align": "^0.1.3","require-main-filename": "^1.0.1","remove-trailing-separator": "^1.0.2","safe-buffer": "^5.1.0","ripemd160": "^2.0.1","semver": "^5.3.0","set-immediate-shim": "^1.0.1","set-blocking": "^2.0.0","setimmediate": "^1.0.5","sha.js?1.1.11": "^2.4.8","source-list-map": "^1.1.2","spdx-correct": "^1.0.2","spdx-license-ids": "^1.2.2","stream-browserify": "^2.0.1","spdx-expression-parse": "^1.0.4","stream-http": "^2.7.1","string-width": "^1.0.2","strip-bom": "^2.0.0","supports-color": "^3.2.3","timers-browserify": "^2.0.2","tapable": "^0.2.6","to-arraybuffer": "^1.0.1","tty-browserify": "^0.0.0","uglify-to-browserify": "^1.0.2","util": "^0.10.3","url": "^0.11.0","validate-npm-package-license": "^3.0.1","util-deprecate": "^1.0.2","vm-browserify": "^0.0.4","watchpack": "^1.3.1","webpack-sources": "^0.2.3","webpack": "^2.6.1","which-module": "^1.0.0","window-size": "^0.1.0","wordwrap": "^0.0.2","wrap-ansi": "^2.1.0","xtend": "^4.0.1","y18n": "^3.2.1","yargs": "^6.6.0","yargs-parser": "^4.2.1"
  },  "description": ""}
View Code

webpack.config.js

var htmlWebpackPlugin =  require('html-webpack-plugin');var path = require('path');

module.exports = {
    entry:{
        main:"./src/app.js?1.1.11",
    } ,
    output:{
        path:__dirname+'/dist',
        filename:'js/[name].bundle.js',//publicPath:'http://hotdeals.com/'    },
    module:{
        loaders:[
            {
                test: /\.js$/,
                loader: 'babel-loader',
                include: path.resolve(__dirname,'src'),
                exclude: path.resolve(__dirname,'node_modules'),
                query:{
                    presets:["es2015"]
                }
             },{
                 test:/\.html/,
                 loader:'html-loader' },
             {
                 test:/\.css$/,
                 loader: [                  'style-loader',
                  { loader: 'css-loader', options: { importLoaders: 1 } },                  'postcss-loader']
             },{
                 test:/\.less$/,
                 loader:'style-loader!css-loader!postcss-loader!less-loader' },
             {
                 test:/\.(jpe?g|png|gif|svg)$/i,
                 loaders:[                     'file-loader?limit=200&name=assets/[name]-[hash:5].[ext]',
                     {
                        loader: 'image-webpack-loader',
                        query: {
                          progressive: true,
                          optimizationLevel: 7,
                          interlaced: false,
                          pngquant: {
                            quality: '65-90',
                            speed: 4  }
                        }
                    }
                 ],
             },
        ]

    },

    plugins:[new htmlWebpackPlugin({
            filename:'index.html',
            template:'index.html',
            inject:'body',
            title:'首页',
        }),
    ]
}
View Code

postcss.config.js(webpack2.0使用css添加前缀,看官网更好)

module.exports = {
  plugins: {'autoprefixer': {},
  }
}
View Code

 

项目文件:

index.html

nbsp;html>


    <meta>
    <title></title>


    <img  src="/static/imghwm/default1.png" data-src="src/assets/songzhixiao.jpeg" class="lazy" alt="Detailed introduction to webpack" >
    <div></div>
    <!-- 我是一行注释 -->

View Code

app.js

import './css/common.css';
import Layer from './components/layer/layer.js';


const App = function(){var dom = document.getElementById('app');var lay = new Layer();
    dom.innerHTML=lay.tpl;
}new App();
View Code

 

 layer.js

import './layer.less'import tpl from './layer.html'function layer(){return {
        name:'layer',
        tpl: tpl
    }
}

export default layer;
View Code

The above is the detailed content of Detailed introduction to webpack. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version