2024-03-13

JavaScript libaries, Vue.js, Ruby on Rails and importmaps.

Here is an example how you can import a JavaScript library to your Vue component when using importmaps in Ruby on Rails

Step 1 - Pin the library in importmaps

Pin your libaray in config/importmaps.rb

pin "axios", to: "https://cdn.skypack.dev/pin/axios@v1.6.7-CtiTWk1RHZKnFCXj0sDG/mode=imports,min/optimized/axios.js", preload: true

Step 2 - Reference the library in your component

// app/javascript/components/HelloWorld.js
import axios from "axios"

const HelloWorld = {
  template: `
    <div>
      <h1></h1>
    </div>
  `,
  data() {
    return {
      message: 'Loading...'
    };
  },
	methods: {
    async fetchData() {
      try {
        const response = await axios.get('https://pokeapi.co/api/v2/pokemon/ditto');
        console.log(response);
        this.message = response.data.name
        // Update your component's data with the fetched data
      } catch (error) {
        console.error('There was an error fetching the data:', error);
        this.message = error
      }
    }
  },
	mounted() {
	  this.fetchData();
	},      
}

export default HelloWorld;