yarn可以更高效的管理assets,不用像以前那样费劲的寻找assets对应的gem包

安装yarn(mac)


#替换homebrew源
cd "$(brew --repo)"
git remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/brew.git

cd "$(brew --repo)/Library/Taps/homebrew/homebrew-core"
git remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-core.git

#安装
brew update
brew install yarn

在Rails项目目录下初始化并安装包


#初始化
yarn init

#安装包
yarn add jquery
yarn add bootstrap

会生成如下 WX20180816-101256

Rails引用node_modules中的静态文件


检查node_modules是否在Rails Assets Paths中

irb(main):007:0> Rails.application.config.assets.paths
=> ["app/assets/config",
	"app/assets/images",
	"app/assets/javascripts",
	"app/assets/stylesheets",
	"vendor/assets/javascripts",
	"vendor/assets/stylesheets",
	"~/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/coffee-rails-4.2.2/lib/assets/javascripts",
	"~.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/actioncable-5.2.1/lib/assets/compiled",
	"~.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/activestorage-5.2.1/app/assets/javascripts",
	"~.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/actionview-5.2.1/lib/assets/compiled",
	"~.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/turbolinks-source-5.1.0/lib/assets/javascripts",
	#<Pathname:vendor/assets>,
	#<Pathname:node_modules>]

如果不存在需在application.rb中加入

    Rails.application.config.assets.paths << Rails.root.join("node_modules")

引用javascript

每个包的引用路径不一样,具体可查看package.json中的main属性 WX20180816-102028

//= require moment/moment

WX20180816-101827

//= require angular-ui-router/release/angular-ui-router

引用css

WX20180816-102519

 *= require select2/dist/css/select2.min

WX20180816-102434

 *= require font-awesome/css/font-awesome

让Rails支持直接使用NPM安装的一些库


gem "browserify-rails"

在package.json中加入

{
  "name": "something",
  "dependencies" : {
    "browserify": "^14.0.0",
    "browserify-incremental": "^3.1.0"
  },
  "license": "MIT",
  "engines": {
    "node": ">= 0.10"
  }
}

然后执行

npm install

这样Rails完成了新的assets管理方式,如果是前后端分离的项目,可以引入webpack。

相关资料