首页 > 解决方案 > 从 Rails 资产管道中获取未缩小的 JS

问题描述

如何从终端运行 rails assets 管道以获取未缩小的 javascript?

我能够运行RAILS_ENV=development bundle exec rake assets:precompile,但这似乎已经生成了捆绑包,而我正在寻找的只是将所有咖啡脚本转译为 javascript,但不缩小也不捆绑。我们只需要从我们的代码库中删除 coffeescript。

我也尝试过 npm 模块 decaffeinate,但这会从 rails 资产管道产生不同的结果,并破坏我们所有的测试。

标签: ruby-on-railsasset-pipelinesprockets

解决方案


有人指导我看这篇文章: http ://scottwb.com/blog/2012/06/30/compile-a-single-coffeescript-file-from-your-rails-project/我更新了它给我选项在目录上递归运行,或在单个文件上运行一次。我添加了这个lib/tasks/,它就像一个魅力。我为 sprockets 风格的指令添加了一个测试,它以 开头#= require,因为 CoffeeScript 编译器会删除所有注释,这会导致一切中断。相反,我手动将所有跳过的文件转换为 JS 并将指令包含为//= require,并且有效。

namespace :coffee do

  def do_one(filepath)
    File.write(filepath.chomp(".coffee"), CoffeeScript.compile(File.open(filepath)))
    File.rename(filepath, filepath.chomp(".js.coffee") + ".backup")
  end

  def cs_task(path)
    Dir.glob("#{path.chomp("/")}/*.js.coffee").each do |filename|
      file = File.open(filename)

      if (file.read[/\= require/])
        puts "skip #{filename}"
      else
        puts "process #{filename}"
        do_one(filename)
      end
    end
    Dir.glob("#{path.chomp("/")}/*/").each do |child_path|
      cs_task(child_path)
    end
  end

  task :cancel, :path do |t, args|
    cs_task(args.path)
  end

  task :show, :path do |t, args|
    puts CoffeeScript.compile(File.open(args.path))
  end

  task :one_off, :path do |t, args|
    do_one(args.path)
  end
end

推荐阅读