LoginSignup
3
3

More than 3 years have passed since last update.

webpackでモジュール間で共通変数を持ちたい

Last updated at Posted at 2019-06-13

2020/05/10追記

うまくいかず、、

hoge.jsでの変更が huga.jsに反映されませんでした。
定数の扱いになってしまうみたいで、
huga.jsの glogals.a は、10のまま。。

これを試しても、やはり同じ感じです。
https://webpack.js.org/plugins/provide-plugin/

webpackの仕様が変わったのか。
とりあえず、windowオブジェクトに名前空間用意するしかないかなぁ。。

誰か知っているかた、おしえてください!

jsファイル間で変数を共有したい時

その昔は、、、

globals.js
(function(){}(
 window.common = {
  a:10,
  b:12
}
))();
a.js
(function(){}(
 window.common = window.common || {}
 window.common.a++;
 console.log(window.common.a); // 11
))();

b.js
(function(){}(
 window.common = window.common || {}
 window.common.a++;
 console.log(window.common.a); // 12
))();
index.html
<html>
<title>バンドルツール出る前の旧石器時代</title>
<head>
</head>
<body>
<script src="./globals.js">
<script src="./a.js">
<script src="./b.js">
</body>

こんなことしてた

webpack使った時

同じ事したい時、どうすればいいのか。
この記事を見て、実験してみたらうまいこといった。
ES6 Modules 間では export/import された変数(?)は同期される

globals.js
export default {
  a:10,
  b:15
};
module_hoge.js
import globals from './globals';
console.log(globals.a) // 10
globals.a++;
console.log(globals.a) // 11
module_huga.js
import globals from './globals';
console.log(globals.a) // 11

:relaxed:

この方法は正しいのだろうか。
他にも色々ありそう。
https://stackoverflow.com/questions/37656592/define-global-variable-with-webpack

3
3
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
3
3