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

需要首先安装 nodejs

1. 全局安装 Webpack

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

npm install webpack -g

2. 在项目中安装 Webpack

2.1 创建package.json配置文件
npm init

新创建的 package.json 内容应该如下所示:

{
  "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 命令。

npm install webpack --save-dev

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

--save-dev 还可以简化为大写的 S,写成 --S。

npm i webpack --S

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

{
    "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 ,保存在根目录下

(function hello(){
    console.log("Hello, Webpack!");
})();
3.1 创建 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: 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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值