我尝试使用yarn
导入date-fns
库到Rails项目,但它没有工作。
我用yarn
来安装date-fns
:
yarn add date-fns
安装它们后,我尝试将此库导入app/javascript/packs/application.js
文件,但它不起作用:
// 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";
我得到一个错误:
> format(new Date(2014, 1, 11), 'yyyy-MM-dd')
> VM498:1 Uncaught ReferenceError: format is not defined
at <anonymous>:1:1
如果我尝试使用app/assets/javascripts/application.js
文件导入它:
//= 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"));
似乎库是连接的,所以我可以调用方法format
,但我得到了另一个错误:
> 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);
我做错了什么?
在Webpack和Rails中导入库的方法是通过yarn安装它,就像你所做的那样,然后在应用程序包中需要它。
# console
$ yarn add date-fns
# app/javascript/packs/application.js
require("date-fns")