我想在我的Stimulus js 控制器中使用dayjs库(而不是 moment),但我不断收到一条错误消息:
dayjs 未定义
setNextVisit(event) {
console.log( dayjs().format('YYYY-MM-DD') );
}
我正在使用带有 Webpacker 和 Stimulus 的 Rails 5.2。
我添加了dayjs通过yarn add dayjs --save
它添加到/package.json
:
/package.json
{
"name": "meh",
"private": true,
"dependencies": {
"@rails/ujs": "^6.0.0-alpha",
"@rails/webpacker": "3.5",
"dayjs": "^1.8.2"
"stimulus": "^1.1.1",
"turbolinks": "^5.2.0"
},
"devDependencies": {
"webpack-dev-server": "2.11.2"
}
}
为了通过 webpacker gem 在 webpack 中连接 dayjs,我将其添加到/app/javascript/packs/application.js
:
/app/javascript/packs/application.js
/* eslint no-console:0 */
// @RAILS/UJS
// imported in config/webpack/environment.js
Rails.start();
// TURBOLINKS
import Turbolinks from 'turbolinks';
Turbolinks.start();
// DAYJS
import dayjs from 'dayjs'
// STIMULUS
import { Application } from 'stimulus'
import { definitionsFromContext } from "stimulus/webpack-helpers"
const application = Application.start()
const context = require.context("./controllers", true, /\.js$/)
application.load(definitionsFromContext(context))