Webpack 入门指南 - 1.安装

时间:2023-03-08 18:24:09
Webpack 入门指南 - 1.安装

Webpack 是目前流行的打包工具,如何安装它呢?

1. 安装 Node Js

首先,Webpack 是基于 NodeJs 的工具,你必须首先安装 NodeJs. NodeJs 仅仅只需要在你的系统中安装一次就可以了。

2. 全局安装 Webpack

我们希望能够在系统的任何文件夹中使用 Webpack,使用的方式是通过 Webpack 命令来完成的,这需要我们全局安装 Webpack。这也只需要安装一次,以后每个项目就不需要重新全局安装了。

$ npm install webpack -g

成功安装之后,你应该能够在任何目录中执行 webpack 命令,如果你还没有项目的配置文件的话,应该会看到当前的 Webpack 版本和一个命令的帮助列表。

> webpack
webpack 1.12.
Usage: https://webpack.github.io/docs/cli.html Options:
--help, -h, -?
--config
--context
--entry
--module-bind
--module-bind-post
--module-bind-pre
--output-path
--output-file
--output-chunk-file
--output-named-chunk-file
--output-source-map-file
--output-public-path
--output-jsonp-function
--output-pathinfo
--output-library
--output-library-target
--records-input-path
--records-output-path
--records-path
--define
--target
--cache [default: true]
--watch, -w
--watch which closes when stdin ends
--watch-aggregate-timeout
--watch-poll
--hot
--debug
--devtool
--progress
--resolve-alias
--resolve-loader-alias
--optimize-max-chunks
--optimize-min-chunk-size
--optimize-minimize
--optimize-occurence-order
--optimize-dedupe
--prefetch
--provide
--labeled-modules
--plugin
--bail
--profile
-d shortcut for --debug --devtool sourcemap --output-pathinfo
-p shortcut for --optimize-minimize
--json, -j
--colors, -c
--sort-modules-by
--sort-chunks-by
--sort-assets-by
--hide-modules
--display-exclude
--display-modules
--display-chunks
--display-error-details
--display-origins
--display-cached
--display-cached-assets
--display-reasons, --verbose, -v Output filename not configured.
PS C:\study\webpack\w1>

注意,最后还提示你,当前没有找到 webpack 配置文件。

3. 在项目中安装 Webpack

最好在你的项目中也包含一份独立的 Webpack,这样你更方便管理你的项目。为什么又是全局安装,又是局部安装呢?可以参考这里的说明

3.1 确认创建 NPM 项目文件

首先,你需要已经创建了 NPM 的项目文件,如果没有的话,使用 init 命令创建它。

 npm init

你需要回答一系列问题。最终你会得到一个名为 package.json 的 NPM 项目文件,如果你愿意的话,手工创建它也不错。甚至你可以直接复制一个过来。

一个新创建的 package.json 内容应该如下所示。

{
"name": "w1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}

3.2 在项目中安装 Webpack

现在,可以在项目中安装 Webpack 了,直接使用 NPM 的 install 命令。

npm install webpack --save-dev

--save-dev 的意思是说 webpack 是一个开发工具,我们需要将这一点保存到 package.Json 文件中。

install 命令可以简化为单个字符 i,注意是小写的 i。

--save-dev 还可以简化为大写的 S,写成 -S,你可以在这里查看 instal 的更详细使用说明

npm i webpack --S

你应该看到一个长长的输出,这是由于 Webpack 是一个很复杂的工具。它依赖很多的其它工具。

> npm install webpack --save-dev
w1@1.0. w1
`-- webpack@1.13.
+-- acorn@3.3.
+-- async@1.5.
+-- clone@1.0.
+-- enhanced-resolve@0.9.
| +-- graceful-fs@4.1.
| `-- memory-fs@0.2.
+-- interpret@0.6.
+-- loader-utils@0.2.
| +-- big.js@3.1.
| +-- emojis-list@2.1.
| +-- json5@0.5.
| `-- object-assign@4.1.
+-- memory-fs@0.3.
| +-- errno@0.1.
| | `-- prr@0.0.
| `-- readable-stream@2.1.
| +-- buffer-shims@1.0.
| +-- core-util-is@1.0.
| +-- inherits@2.0.
| +-- isarray@1.0.
| +-- process-nextick-args@1.0.
| `-- util-deprecate@1.0.
+-- mkdirp@0.5.
| `-- minimist@0.0.
+-- node-libs-browser@0.6.
| +-- assert@1.4.
| +-- browserify-zlib@0.1.
| | `-- pako@0.2.
| +-- buffer@4.9.
| | +-- base64-js@1.2.
| | `-- ieee754@1.1.
| +-- console-browserify@1.1.
| | `-- date-now@0.1.
| +-- constants-browserify@0.0.
| +-- crypto-browserify@3.2.
| | +-- pbkdf2-compat@2.0.
| | +-- ripemd160@0.2.
| | `-- sha.js@2.2.
| +-- domain-browser@1.1.
| +-- events@1.1.
| +-- http-browserify@1.7.
| | `-- Base64@0.2.
| +-- https-browserify@0.0.
| +-- os-browserify@0.1.
| +-- path-browserify@0.0.
| +-- process@0.11.
| +-- punycode@1.4.
| +-- querystring-es3@0.2.
| +-- readable-stream@1.1.
| | `-- isarray@0.0.
| +-- stream-browserify@1.0.
| | `-- readable-stream@1.1.
| | `-- isarray@0.0.
| +-- string_decoder@0.10.
| +-- timers-browserify@1.4.
| +-- tty-browserify@0.0.
| +-- url@0.10.
| | +-- punycode@1.3.
| | `-- querystring@0.2.
| +-- util@0.10.
| | `-- inherits@2.0.
| `-- vm-browserify@0.0.
| `-- indexof@0.0.
+-- optimist@0.6.
| `-- wordwrap@0.0.
+-- supports-color@3.1.
| `-- has-flag@1.0.
+-- tapable@0.1.
+-- uglify-js@2.6.
| +-- async@0.2.
| +-- source-map@0.5.
| +-- uglify-to-browserify@1.0.
| `-- yargs@3.10.
| +-- camelcase@1.2.
| +-- cliui@2.1.
| | +-- center-align@0.1.
| | | +-- align-text@0.1.
| | | | +-- longest@1.0.
| | | | `-- repeat-string@1.5.
| | | `-- lazy-cache@1.0.
| | +-- right-align@0.1.
| | `-- wordwrap@0.0.
| +-- decamelize@1.2.
| `-- window-size@0.1.
+-- watchpack@0.2.
| +-- async@0.9.
| `-- chokidar@1.6.
| +-- anymatch@1.3.
| | +-- arrify@1.0.
| | `-- micromatch@2.3.
| | +-- arr-diff@2.0.
| | | `-- arr-flatten@1.0.
| | +-- array-unique@0.2.
| | +-- braces@1.8.
| | | +-- expand-range@1.8.
| | | | `-- fill-range@2.2.
| | | | +-- is-number@2.1.
| | | | +-- isobject@2.1.
| | | | `-- randomatic@1.1.
| | | +-- preserve@0.2.
| | | `-- repeat-element@1.1.
| | +-- expand-brackets@0.1.
| | | `-- is-posix-bracket@0.1.
| | +-- extglob@0.3.
| | +-- filename-regex@2.0.
| | +-- kind-of@3.0.
| | | `-- is-buffer@1.1.
| | +-- normalize-path@2.0.
| | +-- object.omit@2.0.
| | | +-- for-own@0.1.
| | | | `-- for-in@0.1.
| | | `-- is-extendable@0.1.
| | +-- parse-glob@3.0.
| | | +-- glob-base@0.3.
| | | `-- is-dotfile@1.0.
| | `-- regex-cache@0.4.
| | +-- is-equal-shallow@0.1.
| | `-- is-primitive@2.0.
| +-- async-each@1.0.
| +-- glob-parent@2.0.
| +-- is-binary-path@1.0.
| | `-- binary-extensions@1.7.
| +-- is-glob@2.0.
| | `-- is-extglob@1.0.
| +-- path-is-absolute@1.0.
| `-- readdirp@2.1.
| +-- minimatch@3.0.
| | `-- brace-expansion@1.1.
| | +-- balanced-match@0.4.
| | `-- concat-map@0.0.
| `-- set-immediate-shim@1.0.
`-- webpack-core@0.6.
+-- source-list-map@0.1.
`-- source-map@0.4.
`-- amdefine@1.0. npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: fsevents@1.0.
npm WARN w1@1.0. No description
npm WARN w1@1.0. No repository field.
>

这时候,你再检查一下 package.json 文件,它应该多了三行。

{
"name": "w1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {},
"devDependencies": {
"webpack": "^1.13.2"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}

4.  Hello, Webpack

4.1 打包普通脚本文件

写一段普通的脚本,例如,一个 Hellowrold 脚本。当然了,这里应该是 Hello,Webpack.

function hello(){
alert("Hello, Webpack!");
}

保存到你的项目根目录中,文件名就叫 hello.js

4.2 创建 Webpack 配置文件

Webpack 根据配置文件的配置来完成打包,默认的配置文件名称是 webpack.config.js。

Webpack 的工作很简单,就是打包,你需要告诉它打包的内容,还有输出到哪里。entry 就是入口,显然 output 就是输出。

我们让 Webpack 将 hello.js 文件打包后输出到 bundle.js 文件中。

module.exports = {
// 入口
entry: "./hello.js",
// 输出的文件名
output: {
filename: 'bundle.js'
}
};

在命令窗口,输入 webpack 回车执行。应该会看到如下的输出。

> webpack
Hash: 05c39d9076887c35f015
Version: webpack 1.13.2
Time: 59ms
Asset Size Chunks Chunk Names
bundle.js 1.44 kB 0 [emitted] main
[0] ./hello.js 51 bytes {0} [built]
>

默认的入口文件名为 index.js,如果你将 hello.js 改名为 index.js,还可以直接使用目录名,不用提供文件名。

module.exports = {
// 入口,默认入口文件名为 index.js
entry: ".",
// 输出的文件名
output: {
filename: 'bundle.js'
}
};

生成的 bundle.js 文件内容为

/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {}; /******/ // The require function
/******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ }; /******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded
/******/ module.loaded = true; /******/ // Return the exports of the module
/******/ return module.exports;
/******/ } /******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules; /******/ // expose the module cache
/******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__
/******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports) { function hello(){
alert("Hello, Webpack!");
} /***/ }
/******/ ]);

最后就是我们的脚本。

4.2 将脚本嵌入到网页中

刚刚只是一段脚本,还需要放到网页中才能执行。我们可以安装一个自动帮我们生成宿主网页的 webpack 插件 html-webpack-plugin 来帮助我们。

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

应该会看到如下的输出。

> npm install html-webpack-plugin --save-dev
w1@1.0. w1
`-- html-webpack-plugin@2.24.
+-- bluebird@3.4.
+-- html-minifier@3.1.
| +-- change-case@3.0.
| | +-- camel-case@3.0.
| | +-- constant-case@2.0.
| | +-- dot-case@2.1.
| | +-- header-case@1.0.
| | +-- is-lower-case@1.1.
| | +-- is-upper-case@1.1.
| | +-- lower-case@1.1.
| | +-- lower-case-first@1.0.
| | +-- no-case@2.3.
| | +-- param-case@2.1.
| | +-- pascal-case@2.0.
| | +-- path-case@2.1.
| | +-- sentence-case@2.1.
| | +-- snake-case@2.1.
| | +-- swap-case@1.1.
| | +-- title-case@2.1.
| | +-- upper-case@1.1.
| | `-- upper-case-first@1.1.
| +-- clean-css@3.4.
| | +-- commander@2.8.
| | `-- source-map@0.4.
| +-- commander@2.9.
| | `-- graceful-readlink@1.0.
| +-- he@1.1.
| +-- ncname@1.0.
| | `-- xml-char-classes@1.0.
| +-- relateurl@0.2.
| `-- uglify-js@2.7.
| `-- async@0.2.
+-- lodash@4.16.
+-- pretty-error@2.0.
| +-- renderkid@2.0.
| | +-- css-select@1.2.
| | | +-- boolbase@1.0.
| | | +-- css-what@2.1.
| | | +-- domutils@1.5.
| | | | `-- dom-serializer@0.1.
| | | | +-- domelementtype@1.1.
| | | | `-- entities@1.1.
| | | `-- nth-check@1.0.
| | +-- dom-converter@0.1.
| | | `-- utila@0.3.
| | +-- htmlparser2@3.3.
| | | +-- domelementtype@1.3.
| | | +-- domhandler@2.1.
| | | +-- domutils@1.1.
| | | `-- readable-stream@1.0.
| | | `-- isarray@0.0.
| | +-- strip-ansi@3.0.
| | | `-- ansi-regex@2.0.
| | `-- utila@0.3.
| `-- utila@0.4.
`-- toposort@1.0. npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: fsevents@1.0.
npm WARN w1@1.0. No description
npm WARN w1@1.0. No repository field.
>

这说明这个插件安装好了。

配置 Webpack 使用这个插件,帮助我们生成一个网页,然后将打包的脚本自动插入到这个网页中。

var HtmlwebpackPlugin = require('html-webpack-plugin');

module.exports = {
// 入口
entry: ".",
// 输出的文件名
output: {
filename: 'bundle.js'
},
// 添加我们的插件 会自动生成一个html文件
plugins: [
new HtmlwebpackPlugin({
title: 'Hello Webpack'
})
]
};

其实,这个配置文件就是一段程序,注意第一行,一定要加上。

重新执行 webpack 命令。你会看到多生成了一个名为 index.html 的网页。

> webpack
Hash: 05c39d9076887c35f015
Version: webpack 1.13.
Time: 560ms
Asset Size Chunks Chunk Names
bundle.js 1.44 kB [emitted] main
index.html bytes [emitted]
[] ./index.js bytes {} [built]
Child html-webpack-plugin for "index.html":
+ hidden modules
>

打开这个网页,检查插入的脚本引用。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello Webpack</title>
</head>
<body>
<script type="text/javascript" src="bundle.js"></script></body>
</html>

5. 总结

Webpack 是一个基于 NodeJs 的打包工具,我们可以使用它帮助我们将脚本打包,它还可以帮助我们生成宿主网页,并自动将打包之后的脚本嵌入到这个网页中。

Webpack 入门指南 - 2.模块

附录:

html-webpack-plugin 插件的使用说明