2

I'm new to webpacker and yarn. I installed successfully the package with:

yarn add moment

EDIT2:

This is my import

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

Problem: I can't use the "moment" package in my old JS asset files

First works, the other not:

# 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

EDIT1:

Here the key points of the installation process of webpacker:

  1. in gemfile: gem 'webpacker', github: 'rails/webpacker'
  2. Add this line to assets.rb: Rails.application.config.assets.paths << Rails.root.join('node_modules')
  3. Add in %head of application.html.haml this: = javascript_pack_tag 'application'
  4. Restart Rails server and start webpacker

Note: I upgraded my app from Rails 4.2 to 5.0 and later to 5.1; maybe something is missing in my app

4

2 回答 2

10

I has a similar issue that momentjs was being used throughout the app/assets/javascript files and it was included via gem (actually, even worse, rails-assets). Looks like we both needed moment object to be available globally, not just inside the pack. So, the following fixed that for me and I'll keep it around until I get rid of app/assets/javascript files.

import moment from 'moment'

window.moment = moment
于 2018-01-24T10:37:39.527 回答
0

First I thought this is a solution, but it's not: https://github.com/rails/webpacker#resolved-paths

In "/config/webpacker.yml" I added this:

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

An here I imported the files that use "moment.js":

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

=> Still the error

Later I fount this article: 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.

It seems I can't mix the "moment" package with "old" asset JS (?)

于 2017-07-26T22:55:36.497 回答