7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Elixir/Phoenixでjqueryを使う方法

Last updated at Posted at 2016-05-26

環境

Erlang/OTP 21 [erts-10.0.1] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe] [dtrace]
Elixir 1.6.6 (compiled with OTP 20)
macOS Sierra 10.12.6
node v10.5.0

やり方

cd assets
npm install jquery --save

jquery^3.3.1(2018-07-02)assets/package.jsondependenciesに追加されていると思います

assets/package.json
  8  "dependencies": {
  9    "jquery": "^3.3.1",
 10    "phoenix": "file:../deps/phoenix",
 11    "phoenix_html": "file:../deps/phoenix_html"
 12  }

そしてassets/brunch-config.jsnpmの項目を

assets/brunch-config.js
 59   npm: {globals: {
 60     $: "jquery",
 61     jQuery: "jquery"
 62   }}

とするともうjqueryが使えるようになってます

試す

assets/js/hoge.js
$(function() {
  console.log("jquery loaded.")
})
assets/js/app.js
import "./hoge.js"

mix phx.serverで立ち上げる
http://localhost:4000

jquery loaded.とコンソールに表示されていればjqueryの導入は成功です

参考

追記による注意

ここから下は以前の情報です!(2016/05/26に投稿したもの)

環境

Erlang/OTP 18 [erts-7.3] [source] [64-bit] [async-threads:10] [hipe] [kernel-poll:false]
Elixir 1.3.0-dev (7d5233d)
CentOS 7
Phoenix Framework 1.1.4

やり方

brunch-config.js
  npm: {
    enabled: true,
    // Whitelist the npm deps to be pulled in as front-end assets.
    // All other deps in package.json will be excluded from the bundle.
    whitelist: ["phoenix", "phoenix_html", "jquery"] // ← jqueryを追加
  }
web/static/js/app.js
import "phoenix_html"
import $ from "jquery" // ←phoenix_htmlの下に追加
package.json
{
  "repository": {
  },
  "dependencies": {
    "babel-brunch": "~6.0.0",
    "brunch": "~2.1.3",
    "clean-css-brunch": "~1.8.0",
    "css-brunch": "~1.7.0",
    "javascript-brunch": "~1.8.0",
    "uglify-js-brunch": "~1.7.0",
    "phoenix": "file:deps/phoenix",
    "phoenix_html": "file:deps/phoenix_html",
    "jquery": ">= 2.1" ←追加
  }
}

web/static/vender/に使いたいjqueryのjsファイルを追加

npm install --save

なんかインストールしてるみたいなの出る

終わり

試す

web/static/js/hoge.js
$(function() {
  console.log("jquery loaded.");
});
web/static/js/app.js
~
// import ".hoge" // ←Nao000さん指摘ありがとうございました
import "./hoge" // ←追加

mix phoenix.serverで立ち上げる

コンソールにjquery loaded.が表示されていればjqueryが正常に読み込まれてる

7
4
3

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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?