LoginSignup
13
13

More than 5 years have passed since last update.

WebPackことはじめ。とりあえずjQueryを導入する。

Last updated at Posted at 2015-05-09

WebPackBowerでjQueryを導入するところまでやってみました。

外部ライブラリを使う場合は通常どおり、scriptタグで読み込むのですが、あまり便利になった感がないのでbowerを使うようにしてみました。

基本的にはチュートリアルを参考にしています。

bowerの導入から実行までやってみました。

インストール

#bowerをインストール
npm install -g bower

#jQueryをインストール
bower install jquery

#bower.jsonを作成 とりあえず、モジュールの形式はglobalにします。
bower init  

#webpackをインストール -gだと後で参照エラーが起きてしまう。
npm install webpack --save-dev


準備

webpack.config.js
var path = require("path");
var webpack = require("webpack");

module.exports = {
    entry: "./entry.js",
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
    resolve: {
        root: [path.join(__dirname, "bower_components")]
    },
    plugins: [
        new webpack.ResolverPlugin(
            new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
        )
    ]
};

index.html
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <script type="text/javascript" src="bundle.js" charset="utf-8"></script>
    </body>
</html>
entry
var jQuery = require("jquery");//jQueryは任意

jQuery("body").append("Hello"));

確認

ビルド

コマンドを実行

webpack

起動

index.htmlを開くと"Hello"が表示されるはずです。

bundle.jsの中にjQueryが結合されています。

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, __webpack_require__) {

    var jQuery = __webpack_require__(2);

    jQuery("body").append(__webpack_require__(1));
    // document.write("It works.");


/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {

    module.exports = "It works from content.js.";

/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {

    var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
     * jQuery JavaScript Library v2.1.4
     * http://jquery.com/
     *
     * Includes Sizzle.js
     * http://sizzlejs.com/
     *
     * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
     * Released under the MIT license
     * http://jquery.org/license
     *
     * Date: 2015-04-28T16:01Z
     */

    (function( global, factory ) {

        if ( typeof module === "object" && typeof module.exports === "object" ) {
            // For CommonJS and CommonJS-like environments where a proper `window`
            // is present, execute the factory and get jQuery.
            // For environments that do not have a `window` with a `document`
            // (such as Node.js), expose a factory as module.exports.
            // This accentuates the need for the creation of a real `window`.
            // e.g. var jQuery = require("jquery")(window);
            // See ticket #14549 for more info.

嬉しい所

外部JSはbowerでインストールするだけで、requireで読み込めるようになるので、
さくっと開発をはじめることができます。

webpackを使うとビルド環境がさくっとできるのでお手軽です。

はまったところ

チュートリアルをよく読むと書いてあるのですが、
node_moduleの中にwebpackがないと下記が参照エラーがおきてしまいます。

var webpack = require("webpack");

-gでインストールしたので
チュートリアルの通りやってもうまく動かずハマりました。(・・;)

13
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
13