やりたいこと
長いけど、タイトルに書いてある通り。scriptタグで読み込みました。ハイ、動きましたー!ではなくて、
<script src="/path/to/myLibrary.js" type="text/javascript" ></script>
<script>
const mymodule= new MyLibrary.MyModule({"param1": "value1"});
</script>
みたいな事をしたい。
tl; dr
webpack で babel を利用して、トランスパイルするときに library
を指定する。
webpack と npmを利用するライブラリ
webpack.config.js
module.exports = {
~ 省略 ~
entry : {
"MyLibrary" : './src/my-library.js',
},
output : {
library: 'MyLibrary',
libraryTarget: "umd",
filename : '[name].bundle.js',
path : path.resolve(__dirname, './dist')
},
module : {
~ 省略 ~
}
}
./src/my-library.js
class Auth {
constructor(config) {
console.log(JSON.stringify(config));
}
auth( userName, password ) {
// npm のモジュールを利用した認証処理を実装;
}
}
export { Auth }
ブラウザ
index.html
<!-- webpack が出力したファイルを読み込む -->
<script src="'/path/to/MyLibrary.bundle.js" type="text/javascript" ></script>
<script type="text/javascript" >
// webpack.config.js の output.library に指定した名前で グローバルなオブジェクトがある。
// 中身は { "Auth": Authクラス , __esModule: true }
console.log(MyLibrary);
// クラス Authを利用する
const auth = new MyLibrary.Auth({"pool_id": "my_pool_id"});
auth.auth("user-name", "password");
グローバルなオブジェクトを作ってしまうのは気になるけど、無事に呼び出せた。import
で利用で利用するための方法は課題として先送り。
参考資料
公式
- https://webpack.js.org/guides/author-libraries/
- https://webpack.js.org/configuration/output/#outputlibrary