我想在我的dayjs js控制器中使用instead of moment)库(Stimulus,但我不断收到错误消息:


  未定义dayjs


setNextVisit(event) {
  console.log( dayjs().format('YYYY-MM-DD') );
}


javascript - 如何将库添加到Webpacker中以在Stimulus JS Controller 中使用-LMLPHP

我在Webpacker和Stimulus中使用Rails 5.2。

我通过yarn add dayjs --save添加了dayjs,将其添加到/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))

最佳答案

您需要在刺激控制器中而不是在主application.js中导入dayjs

您的控制器应如下所示:

import { Controller } from "stimulus";
import dayjs from 'dayjs'

export default class extends Controller {

  SetNextVisit(event) {
    console.log( dayjs().format('YYYY-MM-DD') );
 }

}


这不是特定于刺激,而是ES6 JS的工作方式

08-27 17:45