首頁 > web前端 > js教程 > 關於webpack的詳細介紹

關於webpack的詳細介紹

零下一度
發布: 2017-06-26 09:08:26
原創
1875 人瀏覽過

Webpack是前端一個工具,可以讓各個模組進行加載,預處理,再進行打包,它能有Grunt或Gulp所有基本功能。

之前使用的是gulp ,進行頁面的css和js,打包壓縮,配置簡單,但是太過瑣碎麻煩,使用sass時,直接在sass裡導入sass文件,容易報錯(不知道怎麼回事)

webpack吸引我的地方:模組化,按需加載,壓縮css,內嵌樣式,獨立樣式。壓縮js,壓縮頁面

參考文章:(1.0版本)

學習影片:(1.0版本)

自己安裝webpack版本2.0(有些地方要注意)

一. 安裝

安裝測試node和npm 

1 $ node -v2 v6.11.0
登入後複製
$ npm -v3.10.10
登入後複製

新資料夾webpack,,進入專案目錄webpack,進行安裝:

1,使用npm init -y產生package.json檔案

npm init -y
登入後複製

2,安裝webpack(看起來像是全域安裝webpack,可以直接在命令列輸入webpack進行打包)

//全局安装
npm install -g webpack
//安装到你的项目目录
npm install --save-dev webpack
登入後複製

 測試webpack版本為:$ webpack -v         2.6.1

配置指令

這是在package.json 檔案中配置的

"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 輸出結果帶彩色,例如:會以紅色顯示耗時較長的步驟

  • profile 輸出效能數據,可以看到每一步的耗時

  • progress 輸出目前編譯的進度,以百分比的形式呈現

  • display-modules 預設情況下node_modules 下的模組會被隱藏,加上這個參數可以顯示這些被隱藏的模組

  • display-error-details 輸出詳細的錯誤訊息

  • #webpack-dev-server 將會開啟熱更新

  • 更多請參考官網 cli

// 开发模式npm run dev// 热更新模式npm run dev-hrm// 发布模式npm run build
登入後複製

 

 

 

## 

 

二. 設定

新webpack.config.js

module.exports = {
登入後複製
  entry:{

    main:"./src/app.js?1.1 .11",<br/>   } ,<br/>//已多次提及的唯一入口文件

+ "/dist",filename: "js/[name].js?1.1.11",
登入後複製

 

#HtmlWebpackPlugin

依據一個簡單的模板,幫你產生最終的Html5檔案

npm install --save-dev html-webpack-plugin
登入後複製
 

    plugins:[new htmlWebpackPlugin({
            filename:&#39;index.html&#39;,
            template:&#39;index.html&#39;,
            inject:&#39;body&#39;,
            title:&#39;首页&#39;,
        }),
    ]
登入後複製
 

Loaders

鼎大名的Loaders登場了!

Loaders是webpack中最令人興奮的功能之一了。透過使用不同的loader,webpack透過呼叫外部的腳本或工具可以對各種各樣的格式的文件進行處理,比如說分析JSON文件並把它轉換為JavaScript文件,或者說把下一代的JS文件(ES6 ,ES7)轉換為現代瀏覽器可以辨識的JS檔。或者說對React的開發而言,合適的Loaders可以把React的JSX檔轉換成JS檔。

<br/>
登入後複製
登入後複製
登入後複製

Loaders需要單獨安裝並且需要在webpack.config.js下的

modules關鍵字下進行配置,Loaders的配置選項包括以下幾個方面:

<br/>
登入後複製
登入後複製
登入後複製

  • test:一個符合loaders所處理的檔案的拓展名的正規表示式(必須)

  • loader :loader的名稱(必須)

  • include/exclude:手動新增必須處理的檔案(資料夾)或封鎖不需要處理的檔案(資料夾) (可選);

  • query:為loaders提供額外的設定選項(可選)

Babel

Babel其實是一個編譯JavaScript的平台,它的強大之處表現在可以透過編譯幫你達到以下目的:

<br/>
登入後複製
登入後複製
登入後複製

  • 下一代的JavaScript標準(ES6 ,ES7),這些標準目前並未被目前的瀏覽器完全的支援;

  • #使用基於JavaScript進行了拓展的語言,例如React的JSX

################################################################################################## #####
// npm一次性安装多个依赖模块,模块之间用空格隔开npm install --save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react
登入後複製
###### ######
{
                test: /\.js$/,
                loader: &#39;babel-loader&#39;,
                include: path.resolve(__dirname,&#39;src&#39;),
                exclude: path.resolve(__dirname,&#39;node_modules&#39;),
                query:{
                    presets:["es2015"]
                }
             }
登入後複製
######CSS,CSS預處理器######首先安裝postcss-loader 和autoprefixer(自動添加前綴的插件)######
npm install --save-dev style-loader css-loader
登入後複製
######
{
                 test:/\.css$/,
                 loader: [                  &#39;style-loader&#39;,
                  { loader: &#39;css-loader&#39;, options: { importLoaders: 1 } },                  &#39;postcss-loader&#39;]
             }
登入後複製
######
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: &#39;babel-loader&#39;,
                include: path.resolve(__dirname,&#39;src&#39;),
                exclude: path.resolve(__dirname,&#39;node_modules&#39;),
                query:{
                    presets:["es2015"]
                }
             },{
                 test:/\.html/,
                 loader:'html-loader' },
             {
                 test:/\.css$/,
                 loader: [                  &#39;style-loader&#39;,
                  { loader: &#39;css-loader&#39;, options: { importLoaders: 1 } },                  &#39;postcss-loader&#39;]
             },{
                 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:&#39;index.html&#39;,
            template:&#39;index.html&#39;,
            inject:&#39;body&#39;,
            title:&#39;首页&#39;,
        }),
    ]
}
登入後複製
View Code

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

module.exports = {
  plugins: {&#39;autoprefixer&#39;: {},
  }
}
登入後複製
View Code

项目文件:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
    <img src="src/assets/songzhixiao.jpeg" alt="">
    <div id="app"></div>
    <!-- 我是一行注释 -->
</body>
</html>
登入後複製
View Code

app.js

import &#39;./css/common.css&#39;;
import Layer from &#39;./components/layer/layer.js&#39;;


const App = function(){var dom = document.getElementById(&#39;app&#39;);var lay = new Layer();
    dom.innerHTML=lay.tpl;
}new App();
登入後複製
View Code

layer.js

import &#39;./layer.less&#39;import tpl from &#39;./layer.html&#39;function layer(){return {
        name:&#39;layer&#39;,
        tpl: tpl
    }
}

export default layer;
登入後複製
View Code

以上是關於webpack的詳細介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板