LoginSignup
7
6

More than 5 years have passed since last update.

静的サイト用の Webpack4 boilerplate を作った

Last updated at Posted at 2018-12-22

はじめに

この記事は、 UUUM Advent Calendar 2018 23日目の記事です。

TL;DR

  • HTMLとJSとCSSをまとめずに、個別に出力するWebpack4の設定を書いたよ
  • ES6, SCSSのコンパイルと、生成HTMLにjs/cssのinline injectはやってくれるよ!
  • ファイルから勝手に生成するから、webpackに追記は必要無し!
  • テンプレートエンジンはejsだよ
  • とはいえディレクトリ構造はわりと自由なので、共通ファイルの置き場所とか好きにしてね
  • 完成品はこちら

動機

Webpack4のboilerplateで、VueとかReact使えないとかSPA要件無しでピンポイントに合ったものがみつからなかった。
VueとかReactとかSPAとかちょっとしたことを一切したくない(できない)場合、
ちょっと古い作りでやる必要があるときなどにwebpack設定を使い回したかった。

ディレクトリ構造

├── README.md
├── dist - 出力先
│   ├── css
│   │   ├── index.css
│   │   └── page1.css
│   ├── js
│   │   ├── index.js
│   │   └── page1.js
│   ├── index.html --- C
│   └── page1.html
├── package.json
├── src
│   ├── partial --- templateから読み込みたいejsファイルを置くところ
│   │   └── partial.ejs
│   ├── js --- templatesの方とファイル名を合わせる必要がある、ない場合はjsが入らないだけだからなくてもよい
│   │   ├── index.js  --- B
│   │   └── page1.js
│   ├── scss --- ファイル名はなんでもいいよ、jsでインポートするかhtmlで読み込むかして使ってね
│   │   ├── a.scss
│   │   └── b.scss
│   └── templates --- ここの構造がそのまま配信するときの生成htmlになります
│       ├── index.ejs  --- A
│       └── page1.ejs
├── webpack.config.js
└── yarn.lock

src/templatesにあるejs(A)に対して、同名のjsファイルがsrc/jsにある場合(B)に、
そのejsに対してコンパイルしたjsを自動的にinjectしたhtmlを生成して、distディレクトリの直下に出力します(C)。

こんなejs

src/templates/index.ejs
<!DOCTYPE html>
<html>
<head>
    <title>hi</title>
</head>
<body>
test
<% include ./src/partial/partial %>
<img src="<%- require("../images/example.jpg") %>" class="hidden_image">
</body>
</html>

があって、こんな同名のindex.jsがある場合

src/js/index.js
import "../scss/index.scss";

const test = "aa";
console.log(test);

こんなhtmlがdist直下に出力されます。
(jsとcssはそれぞれコンパイルされて別々に出力される)

dist/index.html
<!DOCTYPE html>
<html>
<head>
    <title>hi</title>
<link href="css/index.css" rel="stylesheet"></head>
<body>
test
<p>ejs templating </p>
<img class="text" src="images/example.jpg" alt="">
<script type="text/javascript" src="js/index.js"></script></body>
</html>

Gulpでよくない?

公開方法

zeitのnowがめちゃくちゃ早くておすすめ!
登録してcliツールまでインストールされたら

yarn build
now dist

で速攻でデプロイできます!

いつ使える?

ちょっとした静的サイトとか、LPに毛が生えたやつとかを作るとき

課題

  • scssをいちいちjsからインポートするのがダルい
  • 新規ファイル追加したときにHMRが動かない
  • いちいちjsファイルとejsファイルを作成するのがダルい
  • 共通なscssとか、jsとかをいちいちインポートするのがダルい
  • 2階層以上のurlに対応してない
  • ejsの中の別ejsをincludeするときのpath解決
  • ejsの中の画像パス指定にrequireしないといけない

ここらへんを解決したver2を現在誠意作成中です。
できたら記事を上げます!

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