webpackを試す
package.json作成
npmのinitコマンドを作成する。yオプションをつけると全て初期設定でpackage.jsonが作成される。
$ npm init -y
package.json
{
"name": "test2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
または、yarn init -y
でも可
gitignore追加
giboのNodeを使用。
$ gibo dump Node > .gitignore
webpack インストール
yarnを使用。webpackとwebpack-cliをインストール。-Dオプションをつけることで開発環境のみインストールされるようにする。
$ yarn add -D webpack webpack-cli
ビルド
webpackコマンドでビルドすることができる。
デフォルトではsrc/index.jsをdist/main.jsにビルドする。
src/index.js
console.log('hoge')
webpack実行。modeを指定していないのでワーニングが出ている。
$ npx webpack
asset main.js 20 bytes [emitted] [minimized] (name: main)
./src/index.js 19 bytes [built] [code generated]
WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/
webpack 5.11.0 compiled with 1 warning in 143 ms
dist/main.js
console.log("hoge");
jsをバンドルする
hogeモジュールを用意してバンドルする。
src/modules/hoge.js
const a = () => {
console.log('a')
}
export default a
src/index.js
import a from "./modules/hoge";
console.log('hoge')
a();
developmentモードでビルドする。
$ npx webpack --mode=development
asset main.js 4.13 KiB [emitted] (name: main)
runtime modules 668 bytes 3 modules
cacheable modules 117 bytes
./src/index.js 58 bytes [built] [code generated]
./src/modules/hoge.js 59 bytes [built] [code generated]
webpack 5.11.0 compiled successfully in 65 ms
結果。developmentモードだとバンドルはされないらしい。
productionモードでビルドするとmain.jsにバンドルされて1ファイルで完結するようになった。
$ npx webpack --mode=production
asset main.js 60 bytes [emitted] [minimized] (name: main)
orphan modules 59 bytes [orphan] 1 module
./src/index.js + 1 modules 117 bytes [built] [code generated]
webpack 5.11.0 compiled successfully in 153 ms
webpack設定を書く
webpack.config.js に設定を書く。
entoryで読み込むファイルを指定し、outputで書き出すファイルを指定する。
webpack.config.js
const path = require('path')
module.exports = {
entry: path.resolve(__dirname, 'src', 'index.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'main.js',
}
}