Update all Vue component imports to include the .vue extension at the end

The Vue CLI has decided to no longer support extensionless imports, causing compatibility issues with certain VS Code extensions like Vetur.

In order to address this issue, I require all default component imports from a .vue file to include the file extension throughout the entire codebase. Manually updating each file is impractical due to the sheer number of files involved, so an automated solution is needed.

For example:

Original Imports:

import Baz from '@/components/Baz'
import Thing from './LocalThing'
import OtherThing from '../../OtherThing'

Updated Imports:

import Baz from '@/components/Baz.vue'
import Thing from './LocalThing.vue'
import OtherThing from '../../OtherThing.vue'

What is the best method for achieving this across the codebase?

Answer №1

Find and Replace with Regular Expressions

Search for:

^import (.*?)(?<!\.vue)'$

Replace with:

import $1.vue'

Avoid replacing instances that have already been updated.

This method is effective for performing Find/Replace operations in multiple files at once.

Modification Note:

In order to match filenames that specifically end in .vue, you must create a regex pattern based on those file names.

find . -name "*.vue"

Then formulate a regex using the filenames without their extensions:

^import (.*?(?:Baz|LocalThing|OtherThing))(?<!\.vue)'$

Answer №2

During the transition of my project from Vue CLI to Vite, I encountered a similar issue. To address it, I devised a workaround using a custom Node.js script that involves tweaking some configurations:

const path = require('path')
const replace = require('replace-in-file')
const fs = require('fs')

const FILES_TO_MODIFY_GLOB = 'src/**/*.*'
const CUSTOM_ALIAS_PATH = '@/'
const CUSTOM_ALIAS_DESTINATION = 'src/'

const updateImportsWithoutVueExtension = /^import \w+( as \w+)? from '(.*?)(?<!\.vue)'$/gm
let modifiedFilesCount = 0

console.log('\nUpdating imports...\n')

replace.sync({
  //dry: true,
  encoding: 'utf8',
  files: FILES_TO_MODIFY_GLOB,
  from: updateImportsWithoutVueExtension,
  to: (match, g1, importPath, offset, string, file) => {
    const isExternalImport = /^\w/.test(importPath)
    if (isExternalImport) return match

    const currentDir = path.dirname(file)
    const isCustomAliasPath = new RegExp('^' + CUSTOM_ALIAS_PATH).test(importPath)
    let updatedImportPath = isCustomAliasPath
      ? importPath.replace(CUSTOM_ALIAS_PATH, CUSTOM_ALIAS_DESTINATION)
      : path.resolve(currentDir, importPath)

    const isVueFilePresent = fs.existsSync(updatedImportPath + '.vue')
    if (!isVueFilePresent) return match

    const newImport = importPath + '.vue'
    modifiedFilesCount++
    console.log(`${file} import altered to ${newImport}`)
    return match.replace(importPath, newImport)
  }
})

console.log('\n' + modifiedFilesCount + ' updates were successfully made.')

To use this solution, you'll first need to temporarily install this package as a dependency in your project:

npm i replace-in-file

Subsequently, execute the script with the following command:

node <scriptName>.js

I trust that this workaround will assist others facing a similar challenge down the line.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to identify generic return type in TypeScript

My goal is to develop a core dialog class that can automatically resolve dialog types and return values based on the input provided. I have made progress in implementing this functionality, but I am facing challenges with handling the return values. Each ...

Enhance the appearance of Google Maps by incorporating gradient effects, box shadows, or other similar visual

How can I add a linear gradient to Google Maps? Below is my code snippet. HTML <div id="map"></div> CSS #map{ height:100vh; background: linear-gradient(90deg, #f7f8fa 0%, rgba(247, 248, 250, 0) 18.73%), linear-gradient(180deg, # ...

Is there a way to merge these arrays into a single array?

With the current code I am obtaining numerous JSON objects within separate arrays: Here is the code snippet: for (let i=1; i<=150;i++){ fetch(`A valid URL ${i}`) .then(result => result.json()) .then(result => console.log(result.data.results)) ...

Unlock the full potential of integrating external APIs with Next.js

As a newcomer to NextJs, I am facing the task of making calls to an external Python API from my frontend. Upon discovering NextJs's integrated API feature through creating folders in the app directory, namely api/resource/route, I am wondering what th ...

What is the best method to obtain the following id for an image?

Whenever I hover over the li with the number 3, I am getting the wrong number for the next id in the img tag. The first time, I get next id = 4 which is incorrect. But on the second hover, I get next id = 0 which is what I actually need. How can I correctl ...

Issue with Passport Google Oauth login redirection to successful route

I am currently following a tutorial on setting up Google Oauth in my Express app using Passport.js. The tutorial can be found here. Below are the routes defined in my server.js file: // Code snippet here The server.js file also imports configurations fro ...

Detecting repeated keys in a query for a REST connector in loopback

Can anyone help me figure out how to duplicate parameters in a loopback REST connector query? Here's the code snippet I'm working with: details: { 'template': { 'method': 'GET', 'debug': tr ...

What is the mechanism behind image pasting in Firefox's imgur integration?

Start by launching an image editing software and make a copy of any desired image. Avoid copying directly from a web browser as I will explain the reason later on. Navigate to "http://imgur.com" using Firefox. To paste the copied image, simply press Ctrl+V ...

Tips for transferring information from the Data function to AsyncData in Nuxt

Looking for a way to transfer data from the Data function to asyncData in Nuxt. I've attempted the following: data () { return { prevpage: null, nextpage: null, currentPage: 2, pageNumbers: [], pageNumberCount: 0 ...

Chrome and FireFox Encounter Ajax Functionality Issues

This script that I have created works flawlessly on Internet Explorer! However, it encounters a few issues when used on Chrome and Firefox. Specifically, it only functions correctly for the first action performed, but fails to do so for subsequent actions. ...

Using JavaScript to transform JSON information into Excel format

I have tried various solutions to my problem, but none seem to fit my specific requirement. Let me walk you through what I have attempted. function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) { //If JSONData is not an object then JSON.parse will ...

Determine with jQuery whether the img src attribute is null

My HTML structure is as follows: <div class="previewWrapper" id="thumbPreview3"> <div class="previewContainer"> <img src="" class="photoPreview" data-width="" data-height=""><span>3</span> </div> </div> ...

"Multiple instances of JavaScript files seem to be present when using Ajax navigation

Having some difficulties with AJAX navigation. The issue is that the JavaScript files loaded remain in the browser even after the new content is loaded, even when they are no longer in the DOM. These files appear as VM files in the browser console and cont ...

Mastering Angular2: Leveraging TypeScript's Power to Unleash JavaScript ES6 Syntax with

I am having trouble implementing a translation feature using the ng2-translate pipe in my Angular2/Ionic2 app, which is entirely written in JavaScript ES6. However, I have encountered an issue during the setup phase. The code snippets I have found on the ...

Create a discord.js bot that can randomly select and send a picture from a collection of images stored on my computer

I'm currently working on a bot that sends random pictures from an array of images stored on my computer. However, I encountered an issue when trying to embed the image, resulting in the following error message: C:\Users\47920\Desktop&bs ...

How can you use the :not selector in CSS to target specific elements within a group?

Consider the following set of inputs: <div id="group"> <input id="uno" class="red"></input><br/> <input id="dos" class="red"></input><br/> <input id="tres" class="blue"></input><br/ ...

Employing on() for triggering a form submission

I am attempting to attach a submit event handler to a form that may not always be present in the DOM, so I am using .on(): $('body').on("form","submit", function(e){}) However, when checking Firebug, it shows: $("body").on is not a function ...

Ways to verify AJAX Response String when data format is specified as JSON

When using AJAX to retrieve JSON data from a webpage, it's essential to set the responseType to json. If the data processing is successful, a valid JSON string is returned, which works perfectly. However, if there's an error on the webpage, inst ...

The StreamingTextResponse feature is malfunctioning in the live environment

When I share my code, it's an API route in Next.js. In development mode, everything works as expected. However, in production, the response appears to be static instead of dynamic. It seems like only one part of the data is being sent. I'm puzzl ...

Using Three.JS 'OrbitControls' in VueJS application results in a black screen appearing?

Currently, I've been delving into the basic cube exercise on Three.js, and incorporating the three.js cube into my Vue.JS application. Initially, everything was functioning smoothly, with my cube rotating as intended using animate, etc. However, thi ...