In other words: setting up resolvers in Rails, Webpacker and Jest

If you’ve been writing code for Javascript via Webpacker and Rails, you might be coming across thing like requiring javascript code from some directory structure you and your team has built. But then, requiring javascript code in deeply nested folders would eventually look something like this:

import HelloService from "../../../service/HelloService"
import Image from "../../../assets/svgs/hello.svg"

Wouldn’t it be simpler if it looked like this:

import HelloService from "Services/HelloService"
import HelloSvg from "Assets/svgs/hello.svg"

To achieve this, just add an resolve.alias configuration:

const { resolve } = require("path");
const { config } = require("@rails/webpacker");
const rootJavascriptPath = config.source_path;module.exports = {
resolve: {
alias: {
Components: resolve(rootJavascriptPath, "src/components"),
Mixins: resolve(rootJavascriptPath, "src/mixins"),
Plugins: resolve(rootJavascriptPath, "src/plugins"),
Services: resolve(rootJavascriptPath, "src/services")
}
}…

About

Ace Subido

Father. Husband. Likes video games. Senior Software Engineer @ Bloom Solutions. I like writing notes to myself.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store