Rails 5.1 Webpacker – 通过 yarn 添加 moment.js – 如何在旧资产 JS 中使用包

Rails 5.1 Webpacker – added moment.js via yarn – how to use package in old asset JS

我是 webpacker 和 yarn 的新手。我成功安装了软件包:

yarn add moment

编辑2:

这是我的导入

# app/javascript/packs/application.js
import moment from 'moment/moment'
import 'moment/locale/de-ch'

问题:我无法在我的旧 JS 资产文件中使用 "moment" 包

第一个有效,另一个无效:

# in: app/javascript/packs/application.js
console.log('Log: ' + moment([2007, 0, 29]).toNow()) #=> Log: in 10 Jahren

# in app/*assets*/javascripts/application.js
console.log('Log2: ' + moment([2007, 0, 29]).toNow()) #=> Uncaught ReferenceError: moment is not defined

编辑 1:

这里是webpacker安装过程的重点:

  1. 在gem文件中:gem 'webpacker',github:'rails/webpacker'
  2. 将此行添加到 assets.rb:Rails.application.config.assets.paths << Rails.root.join('node_modules')
  3. 在 application.html.haml 的 %head 添加这个:= javascript_pack_tag 'application'
  4. 重启Rails服务器并启动webpacker

注意:我将我的应用程序从 Rails 4.2 升级到 5.0,然后再升级到 5.1;也许我的应用程序中缺少某些东西

起初我认为这是一个解决方案,但事实并非如此:https://github.com/rails/webpacker#resolved-paths

在“/config/webpacker.yml”中我添加了这个:

# /config/webpacker.yml    
resolved_paths: ['app/assets']

这里我导入了使用"moment.js":

的文件
# /app/javascript/packs/application.js
import 'javascripts/<folder>/<some_file_uses_moment>.coffee'

=> 还是报错

后来我发现了这篇文章: http://samuelmullen.com/articles/embracing-change-rails51-adopts-yarn-webpack-and-the-js-ecosystem/

What happened to the Asset Pipeline? Long story short: nothing. You can still use the asset pipeline the way you always have – ”If you like your asset pipeline, you can keep your asset pipeline”. That includes the javascripts/ directory. You can even mix packaged files with “pipelined” files in your views. You just can’t include your packaged files into your “pipelined” files; well, not easily.

看来我无法将 "moment" 包与 "old" 资产 JS (?)

混合使用

我有一个类似的问题,即整个 app/assets/javascript 文件都在使用 momentjs,它是通过 gem 包含的(实际上,更糟糕的是 rails-assets)。看起来我们都需要 moment 对象在全球范围内可用,而不仅仅是在包内。因此,以下内容为我解决了这个问题,我会保留它直到我删除 app/assets/javascript 个文件。

import moment from 'moment'

window.moment = moment