LoginSignup
61
52

More than 5 years have passed since last update.

webpackでライブラリを作る

Posted at

webpack使ってCommonJSで書いているJSの関数をライブラリとして外部に公開したい場合には、ouput.libraryオプションとoutput.libraryTargetオプションを設定し、ビルドする。

webpack.config.js
module.exports = {
  entry: {
    index: './index'
  },
  output: {
    path: __dirname,
    filename: "[name].bundle.js",
    library: "Hoge",
    libraryTarget: "umd"
  }
};
index.js
exports.hello = function (name) {
  console.log("Hello, " + (name || ""));
}

JSはこんなかんじで、webpackを実行しビルドすると上記のwebpack.config.jsの場合、index.bundle.jsが出力される。

// index.bundle.jsが出力される
$ webpack

scriptタグでindex.bundle.jsを読み込むと、Hoge.helloにindex.jsのhello関数が定義されている。

<body>
    <script src="index.bundle.js"></script>
    <script>
        Hoge.hello('pirosikick'); // "Hello, pirosikick"とコンソールに出力
    </script>
</body>

公開するネームスペースを深くしたい場合

上記の例をちょっと変更して、Hoge.Fuga.helloのようにネームスペースを深くしたい場合は、output.libraryに配列を渡せばよい。

webpack.config.js
module.exports = {
  entry: {
    index: './index'
  },
  output: {
    path: __dirname,
    filename: "[name].bundle.js",
    library: ["Hoge", "Fuga"], // ここを配列にする
    libraryTarget: "umd"
  }
};

[name]とすれば、entryオプションで指定しているキーの部分が動的に使用される。(上記例だとindex

webpack.config.js
module.exports = {
  entry: {
    index: './index'
  },
  output: {
    path: __dirname,
    filename: "[name].bundle.js",
    library: ["Hoge", "[name]"], // Hoge.index.helloになる
    libraryTarget: "umd"
  }
};

output.libraryTargetについて

output.libraryTargetは下記の6つから選べる。

  • var
  • umd
  • this
  • amd
  • commonjs
  • commonjs2

bowerなどで公開してscriptタグで読み込む場合は、varumdでよさげ。

varは名前そのまんまでvarで定義される

var Hoge = (ここに定義

umdはここに詳しく書いているが、AMDとかCommonJSとかよく使うやつにだいたい対応した感じで出力してくれる。

参考リンク

61
52
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
61
52