I try to import date-fns
lib using yarn
to Rails project, but it didn't work.
I use yarn
to install date-fns
:
yarn add date-fns
After install them I try to import this lib to app/javascript/packs/application.js
file, but it didn't work:
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
//
import 'core-js/stable';
import 'regenerator-runtime/runtime';
import format from "date-fns/format";
I got an error:
> format(new Date(2014, 1, 11), 'yyyy-MM-dd')
> VM498:1 Uncaught ReferenceError: format is not defined
at <anonymous>:1:1
If I try import it using app/assets/javascripts/application.js
file:
//= require jquery3
//= require jquery_ujs
//= require popper
//= require bootstrap
//= require date-fns/format
console.log("date-fns", format(new Date(2014, 1, 11), "yyyy-MM-dd"));
It seems the library is connected, so I can call the method format
, but I got another error:
> Uncaught ReferenceError: exports is not defined
# refers to this line
> Object.defineProperty(exports, "__esModule", {
> value: true
> });
> exports.default = format;
# and
> Uncaught TypeError: Cannot read property 'default' of undefined
# refers to this line
> function format(dirtyDate, dirtyFormatStr, dirtyOptions) {
> (0, _index10.default)(2, arguments);
What am I doing wrong?
The way to import a library in Webpack and Rails is to install it via yarn, as you did, and then require it in the application pack.
# console
$ yarn add date-fns
# app/javascript/packs/application.js
require("date-fns")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.