简体   繁体   中英

How to add a library to webpacker to use in Stimulus JS Controllers

I want to to use the dayjs library ( instead of moment) within my Stimulus js Controller, but I keep getting an error that says:

dayjs is not defined

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

在此处输入图片说明

I'm using Rails 5.2 with Webpacker and Stimulus.

I added dayjs via yarn add dayjs --save which add this to /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"
  }
}

To wire-up dayjs in webpack via the webpacker gem, I've added this to /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))

You need to import dayjs in your stimulus controller not in the main application.js

Your controller should look something like that:

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

export default class extends Controller {    

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

}

This is not specific to Stimulus but how ES6 JS works

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM