LoginSignup
13
15

More than 5 years have passed since last update.

webpackで複数のモジュールを管理する

Last updated at Posted at 2016-03-09

練習用のRepositoryで複数のExampleを管理したい時がある。
少しハマったのでメモを残す。

1つのwebpack.config.jsで管理する

resolveプロパティのmodulesDirectoriesでモジュールのルートを指定する

webpack.config.js
// es5
'use strict';
...,

var config = {
  ...,
  resolve: {
    extensions: ['', '.json', '.js', '.jsx'],
    modulesDirectories: ['node_modules', path.join(__dirname, 'src', 'module1'), path.join(__dirname, 'src', 'module2')]
  }
};

module.exports = config;

モジュール毎にwebpack.config.jsを用意する

モジュールのディレクトリをルートとしてwebpack.config.jsを同じ階層に配置する。
ReduxのExampleはこの方法を採用しているようです。

directory構造
$ tree -a -I 'node_modules|.git|.DS_Store|dist|lib|.vscode|.gitignore'
├── .babelrc
├── .eslintrc
├── package.json
├── src
│   ├── module1
│   │   ├── class1.js
│   │   ├── index.html
│   │   ├── index.js
│   │   └── webpack.config.js
│   ├── module2
│   │   ├── class1.js
│   │   ├── index.html
│   │   ├── index.js
│   │   └── webpack.config.js
│   ├── module3
│   │   ├── index.html
│   │   ├── index.js
│   │   └── webpack.config.js
│   └── module4
│       ├── index.html
│       ├── index.js
│       ├── modules
│       │   ├── About.js
│       │   ├── App.js
│       │   ├── Repo.js
│       │   ├── Repos.js
│       │   └── style.scss
│       └── webpack.config.js
└── webpack.config.js

ビルドは各モジュールのルートまでcdしてからwebpackをする。
package.jsonnpm run build:module1のようにするscriptを作成するのもありかな?

webpack.config.js
// es5
'use strict';
...,

var config = {
  ...,
  resolve: {
    extensions: ['', '.json', '.js', '.jsx'],
    // __dirnameでモジュールのルートを指定する
    modulesDirectories: ['node_modules', __dirname]
  }
};

module.exports = config;
build
$ cd src/module1
$ webpack

webpackはこれだけでcssimageもバンドルできるのが強みらしいので、どんどん覚えていきたいですね。
特にReact周りはwebpackが良く使われているので尚更ですね。

13
15
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
15