用Webpack建立一个脚本并自动嵌入网页

须要首先安装 nodejsjavascript

1. 全局安装 Webpack

咱们但愿可以在系统的任何文件夹中使用 Webpack,使用的方式是经过 Webpack 命令来完成的,这须要咱们全局安装 Webpack。这也只须要安装一次,之后每一个项目就不须要从新全局安装了。html

npm install webpack -g

2. 在项目中安装 Webpack

2.1 建立package.json配置文件

npm init

新建立的 package.json 内容应该以下所示:java

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

2.2 在项目中安装 Webpack

直接使用 NPM 的 install 命令。node

npm install webpack --save-dev

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

--save-dev 还能够简化为大写的 S,写成 --S。web

npm i webpack --S

这时候, package.json 文件多了三行。npm

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

3.建立一个普通脚本文件而后打包

文件名 hello.js ,保存在根目录下json

(function hello(){
    console.log("Hello, Webpack!");
})();

3.1 建立 Webpack 配置文件

Webpack 默认的配置文件名是 webpack.config.js。
Webpack 的工做就是打包,你须要告诉它打包的内容,以及输出到哪里。entry 就是入口,output 就是输出。
咱们让 Webpack 将 hello.js 文件打包后输出到 bundle.js 文件中。ide

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

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

> webpack
Hash: 3bd1a17d835003ecda85
Version: webpack 2.6.0
Time: 386ms
    Asset     Size  Chunks             Chunk Names
bundle.js  2.68 kB       0  [emitted]  main
   [0] ./hello.js 49 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] = {
/******/             i: moduleId,
/******/             l: false,
/******/             exports: {}
/******/         };
/******/
/******/         // Execute the module function
/******/         modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/         // Flag the module as loaded
/******/         module.l = 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;
/******/
/******/     // identity function for calling harmony imports with the correct context
/******/     __webpack_require__.i = function(value) { return value; };
/******/
/******/     // define getter function for harmony exports
/******/     __webpack_require__.d = function(exports, name, getter) {
/******/         if(!__webpack_require__.o(exports, name)) {
/******/             Object.defineProperty(exports, name, {
/******/                 configurable: false,
/******/                 enumerable: true,
/******/                 get: getter
/******/             });
/******/         }
/******/     };
/******/
/******/     // getDefaultExport function for compatibility with non-harmony modules
/******/     __webpack_require__.n = function(module) {
/******/         var getter = module && module.__esModule ?
/******/             function getDefault() { return module['default']; } :
/******/             function getModuleExports() { return module; };
/******/         __webpack_require__.d(getter, 'a', getter);
/******/         return getter;
/******/     };
/******/
/******/     // Object.prototype.hasOwnProperty.call
/******/     __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/     // __webpack_public_path__
/******/     __webpack_require__.p = "";
/******/
/******/     // Load entry module and return exports
/******/     return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {

(function hello() {
    console.log('Hello, Webpack!');
})();

/***/ })
/******/ ]);

大多都是注释,最后就是咱们的脚本。

3.2 将脚本嵌入到网页中

刚刚只是一段脚本,还须要放到网页中才能执行。咱们能够安装一个自动帮咱们生成宿主网页的 webpack 插件 html-webpack-plugin 来帮助咱们。有关 html-webpack-plugin 使用说明看这里

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

配置 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: 076d7b9f6ae9032d1dd4
Version: webpack 2.6.0
Time: 483ms
     Asset       Size  Chunks             Chunk Names
 bundle.js    2.68 kB       0  [emitted]  main
index.html  184 bytes          [emitted]
   [0] ./index.js 49 bytes {0} [built]
Child html-webpack-plugin for "index.html":
       [0] ./~/lodash/lodash.js 540 kB {0} [built]
       [1] ./~/html-webpack-plugin/lib/loader.js!./~/html-webpack-plugin/default
_index.ejs 538 bytes {0} [built]
       [2] (webpack)/buildin/global.js 509 bytes {0} [built]
       [3] (webpack)/buildin/module.js 517 bytes {0} [built]

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

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello Webpack</title>
  </head>
  <body>
  <script type="text/javascript" src="bundle.js"></script></body>
</html>
相关文章
相关标签/搜索