如何在Rails6内通过Webpacker使用JavaScript;
Rails6默认不再使用asset pipeline,改用Webpacker。
文件结构变化:
- 配置文件: webpacker.yml
- package.json查看安装的js库,可以使用yarn命令或者npm
- app/assets/javascript不会再generate。
- app/javascript/packs/application.js:packs文件夹管理独立安装的包。
下图是默认生成的文件夹。包含了rails UJS库, turbolinks, atcivestorage, channels
添加了channels文件夹。
如何安装一个packer:
# 例如 rails webpacker:install:stimulus
Appending Stimulus setup code to /Users/.../tailwindapp/app/javascript/packs/application.js append app/javascript/packs/application.js
# 增加了一行代码import "controllers"
Creating controllers directory create app/javascript/controllers create app/javascript/controllers/hello_controller.js create app/javascript/controllers/index.js Installing all Stimulus dependencies run yarn add stimulus from "."
#安装依赖包,可以在yarn.lock中看到详细说明
使用Flatpickr
一个轻量化的datetime picker。
包括使用JS和CSS
安装:
# using npm install npm i flatpickr --save # 其他 yarn add flatpickr #cdn也可以
use
推荐直接使用元素,或者选择器:
// If using flatpickr in a framework, its recommended to pass the element directly flatpickr(element, {}); // Otherwise, selectors are also supported flatpickr("#myID", {}); // creates multiple instances flatpickr(".anotherSelector");
Rails中的使用
1. 生成一个Post
下面的命令仍然会生成assetpipeline的文件: stylesheets/scaffolds.scss,如果不使用就删除掉。
rails g scaffold Post title publish_date:date
2. yarn add flatpickr
javascript/packs/application.js内添加:
import flatpickr from "flatpickr";
#只使用flatpickr的CSS样式
require("flatpickr/dist/flatpickr.css")
#或者使用不同的样式主题
#require("flatpickr/dist/themes/light.css")
document.addEventListener("turbolinks:load", () => {
flatpickr("[data-behavior='flatpickr']", {
altInput: true,
altFormat: "F j, Y",
dateFormat: "Y-m-d"
})
})
在application.html.erb添加:(使用webPacker CSS)
<%= stylesheet_pack_tag 'application', media: "all", ...%>
在对应的视图文件内添加:
<div> <%= form.text_field :publish_date, data: {behavior: 'flatpickr'}%> </div>
#生成<input data-behavior="flatpickr" type="hidden" name="post[publish_date]" id="post_publish_date" class="flatpickr-input">