LoginSignup
4
2

More than 3 years have passed since last update.

middleman4とwebpack

Last updated at Posted at 2019-08-08

middleman4のディレクトリにwebpackとcliをインストールする

npm init
npm install --save-dev webpack webpack-cli

package.jsonの編集

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1"
},

この部分に以下のように2行追記する

"scripts": {
  "develop": "webpack --config ./webpack.config.js --watch -d --progress --colors",
  "build": "webpack --config ./webpack.config.js --bail -p",
  "test": "echo \"Error: no test specified\" && exit 1"
},

config.rbの編集

以下のコードを好きなところに追記する

activate :external_pipeline, {
  name: :webpack,
  command: build? ?
    "NODE_ENV=production npm run build" :
    "NODE_ENV=develop npm run develop",
  source: "./build",
  latency: 1
}

webpack.config.jsの作成と編集

config.rbと同じ階層にwebpack.config.jsを作成

const webpack = require('webpack');

module.exports = {
  entry: [
    './source/javascripts/site.js'
  ],
  output: {
    filename: 'site.js',
    path: __dirname + '/build/javascripts'
  }
};
vi webpack.config.js
上記をコピペ
:wq

gitignoreの編集

以下を追記し監視から除外する

node_modules/

動作確認

bundle exec middleman
で起動してみる

== The Middleman is loading
== Executing: `NODE_ENV=develop npm run develop`
== External: > template@1.0.0 develop /Users/***/Sites/mysites/***
== External: > webpack --config ./webpack.config.js --watch -d --progress --colors
10% building 1/1 modules 0 active
webpack is watching the files…

== External: Hash: a0a5f17ceb65673f14d8
== External: Version: webpack 4.39.1
== External: Time: 76ms
== External: Built at: 2019/08/08 17:11:39
== External:     Asset      Size  Chunks             Chunk Names
== External: bundle.js  4.63 KiB    main  [emitted]  main
== External: Entrypoint main = bundle.js
== External: [0] multi ./source/javascripts/site.js 28 bytes {main} [built]
== External: [./source/javascripts/site.js] 55 bytes {main} [built]
== View your site at "http://localhost:4567", "http://127.0.0.1:4567"
== Inspect your site configuration at "http://localhost:4567/__middleman", "http://127.0.0.1:4567/__middleman"

こんなんが出ればOK

JSファイルをバンドルする

views.jsというファイルをエントリーポイントに指定したJSにバンドルする例

views.js
console.log('hoge');

以下を記述

***.js
import views from './views'

以下のコマンドを叩く

webpack
Hash: 9bbc245da56ed4feec28
Version: webpack 4.39.2
Time: 65ms
Built at: 2019/08/20 15:46:21
  Asset      Size  Chunks             Chunk Names
site.js  4.97 KiB    main  [emitted]  main
Entrypoint main = site.js
[0] multi ./source/javascripts/***.js 28 bytes {main} [built]
[./source/javascripts/***.js] 60 bytes {main} [built]
[./source/javascripts/views.js] 24 bytes {main} [built]

JSにCSSをバンドルする

SASS(SCSS)を使っている場合です。
まず、必要なパッケージをインストールします。

npm install --save-dev style-loader css-loader sass-loader node-sass

任意のスタイルファイルを用意する
例題はstylesheetsディレクトリ内にsite.css.scssというファイルを用意してます。

webpack.config.jsの編集

webpack.config.js
const webpack = require('webpack');

module.exports = {
  mode: 'production', //追記
  entry: [
    './source/javascripts/site.js'
  ],
  output: {
    filename: 'site.js',
    path: __dirname + '/build/javascripts'
  },
  module: { //ここから追記
    rules: [
      {
        test: /\.(sc|c|sa)ss$/,
        use: ['style-loader', 'css-loader', 'sass-loader']
      },
    ],
  },
};

site.jsの編集

site.js
import "../stylesheets/site.css.scss"; //追記
import views from './views'

layout等のHAMLの編集

CSSの読み込み行を削除し、JS読み込み行を閉じBODY直上に移動させてます。

layout.erb
<!doctype html>
<html lang='ja'>
  <head>
    <meta charset='utf-8'>
    <meta http-equiv='x-ua-compatible' content='ie=edge'>
    <meta name='viewport'
          content='width=device-width, initial-scale=1, shrink-to-fit=no'>
    <title><%= current_page.data.title || "Middleman" %></title>
  </head>
  <body>
    <%= yield %>
    <%= javascript_include_tag 'site' %>
  </body>
</html>

CSS内の画像をバンドルする

npm install --save-dev url-loader

webpack.config.jsの編集

webpack.config.js
const MODE = 'development';
const webpack = require('webpack');
const enabledSourceMap = MODE === "development";

module.exports = {
  mode: MODE,
  entry: [
    './source/javascripts/site.js'
  ],
  output: {
    filename: 'site.js',
    path: __dirname + '/build/javascripts'
  },
  module: {
    rules: [
      {
        test: /\.(sc|c|sa)ss$/,
        use: [
          "style-loader",
          {
            loader: "css-loader",
            options: {
              url: true,
              sourceMap: enabledSourceMap,
              importLoaders: 2
            }
          },
          {
            loader: "sass-loader",
            options: {
              sourceMap: enabledSourceMap
            }
          }
        ]
      },
      {
        test: /\.(gif|png|jpg|eot|wof|woff|woff2|ttf|svg)$/,
        loader: "url-loader"
      }
    ]
  },
};

【おまけ】JQueryをnpmで管理する

dependenciesでもdevDependencies好きな方どうぞ

npm install --save-dev jquery

jqueryを動作させたいJSファイルに以下を記述

const $ = require('jquey');

環境

ruby 2.6.5p114
npm 6.13.6
middleman 4.3.5

4
2
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
4
2