Can the import path for vuejs app.js be determined dynamically or within an if-else condition?

App.js

Updated

import x from 'project/a'

Is it possible to change it to:

var project = 'a'

if(project == 'a')
{
   import x from 'project/a'
}
else
{
   import x from 'project/b'
}

or would this alternative method work:

var project = 'a'
var filepath = '';

if(project == 'a')
{
   filepath = 'project/a';
}
else
{
   filepath = 'project/b';
}

import x from filepath

Answer №1

There are two ways to approach this:

Option 1: Import both and use a conditional statement

Combine the code for projectA and projectB into one file with a conditional statement.

import initProjectA
import initProjectB

if (condition) {
  initProjectA()
} else {
  initProjectB()
}

When compiled, it will look like this:

function initProjectA() {
}

function initProjectB() {
}

if (condition) {
  //
}

Option 2: Use dynamic imports

With dynamic imports, three separate files will be created: projectA, projectB, and conditional.

import(module).then(importedModule => {
  importedModule.default() // assuming you did `export default`
})

The conditional file will only load and execute one of them based on the condition.

  • Check which project to download
  • Download the file and execute it

To use dynamic imports, you may need to adjust some configurations. Search for "webpack dynamic imports" for more information.

Answer №2

If you want to conditionally import a file in JavaScript, you can follow this approach:

var project = 'a'

let x;

if(project == 'a')
{
   x = require('project/a').default;
}
else
{
   x = require('project/b').default;
}

Make sure you are using export default in the files you are importing.

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

Error: The variable 'err' is undefined in the mongoose mongodb code

Every time I try to execute this code, an error pops up stating that err is undefined Below is the code snippet causing the issue: app.post('/tinder/cards', (req, res) => { const dbCard = req.body; Cards.create(dbCard, (err, data) => { ...

Enhancing a Stripe customer object with additional metadata

While setting up a payment system using Stripe, I encountered an issue when trying to add metadata to the customer object. Specifically, I wanted to include my workspace id in the metadata property of the customer. However, upon executing the code below, I ...

Unable to execute application due to invalid element type

I'm just diving into learning React Native, and as I attempt to launch my app, an error message pops up: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Verif ...

What is the correct way to toggle an icon button?

Hello everyone! I need help with toggling a font-awesome icon on a button using jQuery or JavaScript. I've tried using jQuery, but the previous icon doesn't get removed from the button when toggling to the new icon. Below is the code snippet: < ...

Troubleshooting a glitch with passing a variable to a PHP script using AJAX

Explanation of the page functionality: When the quiz php page loads, a user can create a score using a function in quiz.js. This score is then stored in a variable score within quiz.js Once the score is generated, the user must click a button to move on ...

Retrieve the selected value from a radio button

I am attempting to display the chosen value in an input field when a radio button is selected. However, the functionality seems to be broken when I include bootstrap.min.js. You can find the code on JSFiddle. $('input:radio').click(function() ...

Creating a unique chrome extension that swaps out HTML and JavaScript components

Is there a possibility to create a Chrome extension that eliminates the JavaScript and CSS from a website while it loads, replacing them with new scripts from a separate source? For example, changing 'Old script' to 'new script', or &a ...

jQuery mobile enhancing user experience with dynamic background images

I am having trouble setting different background images for each page in jQuery Mobile. <div data-role="page" id="pageone">... </div> <div data-role="page" id="pagetwo">... </div> Since each page has a unique ID, I tried ...

Exciting Update: Next.js V13 revalidate not triggering post router.push

Currently using Next.js version 13 for app routing, I've encountered an issue with the revalidate feature not triggering after a router.push call. Within my project, users have the ability to create blog posts on the /blog/create page. Once a post is ...

Should we make it a routine to include shared sass variables in each vue component for better practice?

Within my Vue application, there are numerous components that rely on shared variables like colors. I'm considering having each component import a global "variables.scss" file. Would this approach have any adverse effects? ...

Efficient JavaScript File Parsing with the Use of Breakpoints

Currently, I am developing a small web application that requires the user to upload a .csv file, which is then parsed into an array using JavaScript. However, I have encountered an issue where the JavaScript code only functions properly when I have develop ...

Utilizing chart.js data source plugin in React application (react2chartjs)

Upon receiving inspiration from a question regarding importing data from Excel and presenting it as charts using ChartJs (Import data from Excel and use in Chart.js), I was able to successfully achieve this goal. However, my attempt to replicate this proce ...

Implementing Icons in Custom Headers of AG Grid Using vue js

I am working on implementing a new feature in AG Grid where I want to display an info icon in the header along with a tooltip that appears when the icon is hovered over. I have already created a custom tooltip component that works correctly, but once I a ...

Struggling to establish a consistent header on every page in AngularJS

I've been attempting to implement a header that appears on all my pages using AngularJS. Here is the current setup I have: In my HTML file, I've included the following code: <html ng-app="webApp"> <script src="/vendor/angular.min.js"& ...

Tips for turning on a gaming controller before using it

Current Situation In my ionic side menu app, I have a main controller called 'main view'. Each tab in the app has its own controller, which is a child of the main controller. The issue I'm facing is that when I start the app, the first cont ...

Is it possible to determine if a window was opened using window.showModalDialog()?

Is there a way to determine if a window was triggered by window.showModalDialog()? I've noticed that when a new window is opened using window.open(), window.opener correctly returns the parent window. However, when using window.showModalDialog(), wind ...

Strategies for effectively searching and filtering nested arrays

I'm facing a challenge with filtering an array of objects based on a nested property and a search term. Here is a sample array: let items = [ { category: 15, label: "Components", value: "a614741f-7d4b-4b33-91b7-89a0ef96a0 ...

When nodemon is executed, it encounters an "Error: Cannot find module" issue, indicating that it may be searching in the incorrect directory

I recently encountered an issue with my Node.js project that utilizes nodemon. Despite having the package installed (located in /node_modules), I am experiencing an error when trying to start my Express server with nodemon through a script in my package.js ...

Verifying the numerical value of a decimal place

How can I determine if the 4th decimal place in a number is zero or not? I want to throw an error message if it is not zero. For instance, in the number 2.3189, the value of the 4th decimal place is 9. My current code works for most cases, but for exampl ...

Generate selection choices by looping through a JSON document

I am attempting to develop a search box that will provide autocomplete suggestions based on user input from a key-value pair in a json file. I initially thought using datalist would be the most suitable approach for this task, however, upon running the cod ...