【问题标题】:How to import date-fns JS library to Rails project using yarn如何使用 yarn 将 date-fns JS 库导入 Rails 项目
【发布时间】:2021-05-20 06:52:59
【问题描述】:

我尝试使用yarndate-fns lib 导入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 不会将 JS 导出到全局范围。

标签: javascript ruby-on-rails date-fns


【解决方案1】:

在 Webpack 和 Rails 中导入库的方法是通过 yarn 安装它,就像你做的那样,然后在应用程序包中需要它。

# console
$ yarn add date-fns

# app/javascript/packs/application.js
require("date-fns")

【讨论】:

    猜你喜欢
    • 2021-10-08
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 2018-09-08
    • 2021-06-13
    • 2021-09-19
    • 2023-03-09
    相关资源
    最近更新 更多