LoginSignup
4

More than 5 years have passed since last update.

webpackとwebpack-serveで静的なWeb環境を作る(deprecated)

Last updated at Posted at 2018-06-28

webpack-serve さん。メンテモードに入った webpack-dev-server の後継らしいのですが周りであんまり使っている人がいないので、自分が手元で使っている最低限の構成を書いておきます。

追記: webpack-serve も 2系にバージョンアップし、細かいところで挙動が変わっていたりするので、なるべく公式ドキュメントをあたってください。

追記: webpack-serveは開発が止まり、webpack-dev-server の開発が再開しました。したがってwebpack-dev-server を使っていきましょう。

インストールする

npm inint -y
npm install --save-dev webpack webpack-cli webpack-serve

webpack.config.js を作成する

  • webpack4からは設定ファイルがなくても動くが、コマンドラインオプションで bind とかいっぱい書くと package.json のスクリプトがでかくなってコミット差分が読むのつらいので結局あった方がよいという学びを得た。
  • output や entry もデフォルト値があるが、明示的に書いておいたほうがメンテしやすかった。
  • mode指定は webpack-serve のREADME 参照。なお、「webpackのmodeを自動的に設定したい」というイシューはけっこう前からあがっているのだが閉じられたまま進行している。
const path = require('path')

module.exports = {
    mode: process.env.WEBPACK_SERVE ? 'development' : 'production',
    entry: path.resolve(__dirname, "index.js"),
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'main.js'
    }
}

serve.config.js を作成

  • webpack.config.jsserve オプションで書けるのだけど、独立ファイルの方がなにかと便利なのでわける。
  • open: true, port:8080 はオプション。
const serve = require('webpack-serve');
const config = require('./webpack.config.js');
const argv = {}
const options = { config, content: 'public/' ,open: true, port:8080 }

// serve({}, { config });
serve(argv, options);

src/index.js

index.js
var content = document.getElementById("content");
content.innerHTML = "this is content";

public/index.html

index.html
<div id="content"/>
<script src="/main.js" defer></script>

起動

npx webpack-serve

ss.png

起動できた。webpack使っているのは src/ 以下のJSファイルのみで、特に変換も何もしていない状態。

webpack-serve は webpack-hot-client を利用しているため、src 内のファイルを更新すると自動的に再ビルドが行われ、ブラウザで表示しているコンポーネントが書き換えられる。

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
4