LoginSignup
1
0

More than 3 years have passed since last update.

npm で提供されている JavaScriptのライブラリを Webブラウザからライブラリとして呼び出したい

Posted at

やりたいこと

長いけど、タイトルに書いてある通り。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 で利用で利用するための方法は課題として先送り。

参考資料

公式

公式へたどり着くまでに、参考にさせていただいた

1
0
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
1
0