Rails6將默認使用webpack代替asset:javascript
本文講述如何本身配置。css
參考:前端
https://getbootstrap.com/docs/4.1/getting-started/webpack/java
https://github.com/rails/webpackerjquery
https://gorails.com/episodes/how-to-use-bootstrap-with-webpack-and-rails?autoplay=1webpack
安裝:git
//後兩個是依賴 yarn add bootstrap jquery popper.js
配置:github
#config/webpack/environment.js const { environment } = require('@rails/webpacker') const webpack = require('webpack') environment.plugins.append("Provide", new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', Popper: ['popper.js', 'default'] })) module.exports = environment
備註:
new webpack.ProvidePlugin(),自動load模塊無需每次都import或require.
https://webpack.js.org/plugins/provide-plugin
#app/javascript/packs/application.js添加 import 'bootstrap' import '../stylesheets/application' document.addEventListener('turbolinks:load', ()=>{ $('[data-toggle="tooltip"]').tooltip() $('[data-toggle="popover"]').popover() }) #新建app/javascript/stylesheets/application.scss。 @import "~bootstrap/scss/bootstrap";
完成配置!能夠使用Bootrap4了。web
rails5須要手動安裝webpack。rails6默認使用webpack了!bootstrap
app/javascript: ├── packs: │ # only webpack entry files here │ └── application.js └── src: │ └── application.scss └── images: └── logo.svg
在view上使用webpack:
<%= javascript_pack_tag 'application' %>
若是在pack文件中引進了styles:使用👇來連接:
<%= stylesheet_pack_tag 'application' %>
若是連接靜態資源<link><img>標籤,使用:
<link rel="prefetch" href="<%= asset_pack_path 'application.css' %>" /> <img src="<%= asset_pack_path 'images/logo.svg' %>" />
2個binstubs。
# webpack dev server ./bin/webpack-dev-server # watcher ./bin/webpack --watch --colors --progress # standalone build ./bin/webpack
在開發模式下,Webpacker在命令中(on-demand)編譯,不在前端upfront。這個過程發生在使用Webpacker helper methods時。所以無需運行任何獨立的processes。編譯錯誤會記錄在標準的RAils log。
若是想要動態加載(use live code reloading),或者由於JS代碼過多致使on-demand compilation太慢,能夠使用./bin/webpack-dev-server。這個進程會監視app/javascript/packs/*.js文件的變化並自動的在瀏覽器上從新加載。
當你開啓development server, Webpacker會自動代理全部的webpack asset requests給服務器。
當你停動態加載後,會改回使用on-demand compilation。