練習用の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.json
でnpm 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
はこれだけでcss
やimage
もバンドルできるのが強みらしいので、どんどん覚えていきたいですね。
特にReact
周りはwebpack
が良く使われているので尚更ですね。