Webpack is mistakenly looking in the incorrect subfolder when attempting a relative import

I have set up a Vue application (version 3 with TypeScript) within a directory structure where the Vue app is nested inside a directory named /my-vue-app. In the same directory, there is a folder containing my Node.js server code (not TypeScript) that I am using for server-side rendering of the Vue app. Here is how my directory structure looks:

- /app-container
    |
    - /app-container/.babelrc.json
    - /app-container/webpack.server.js
    - /app-container/my-vue-app
       |
       - /app-container/my-vue-app/babel.config.js
       - /app-container/my-vue-app/package.json
       - /app-container/my-vue-app/tsconfig.json
       - /app-container/my-vue-app/public
       - /app-container/my-vue-app/src
          |
          - /app-container/my-vue-app/src/App.ts
          - /app-container/my-vue-app/src/main.ts
          - /app-container/my-vue-app/src/views
             | -- some stuff
          - /app-container/my-vue-app/src/components
             | -- some stuff
          - /app-container/my-vue-app/src/router
             |
             - /app-container/my-vue-app/src/router/index.ts
    - /app-container/server
        |
        - /app-container/server/index.js

While trying to import

/app-container/my-vue-app/src/App.ts
from server/index.js, everything works as expected. However, when attempting to import App.ts from main.ts, I encounter an unusual error stating that the module is 'not found'. I have tried different import syntaxes, but none have been successful except for using an absolute path:

// This does not
import App from "./App";
// Throws error complaining about .ts extension
import App from "App.ts";
// As per `vue create`, @ is configured to /src
import App from "@/App"
// Understandably, this is not found - but it was worth a try
import App from "/my-vue-app/src/App"

// This worked
import App from "C:\\absolute\\path\\to\\app-container\\my-vue-app\\src\\App";

It seems that Webpack is searching in the wrong directory when using "./App", leading to the error. The error only occurs when importing App.ts from the Node app, not during the yarn run serve in /my-vue-app. When using @/App, it attempts to search for it in /my-vue-app/node_modules and /node_modules in the project root.

For reference, here is my webpack.server.js configuration:

module.exports = {
    entry: './server/index.js',
    target: 'node',

    externals: [nodeExternals()],

    output: {
        path: path.resolve('server-build'),
        filename: 'index.js',
    },

    resolve: {
        extensions: ['.tsx', '.ts', '.js', '.jsx', '.css', '.scss', '.sass', '.vue']
    },

    plugins: [new VueLoaderPlugin(), ...],

    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader',
            },
            {
                test: /\.jsx?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                options: {
                    'presets': [
                        '@babel/preset-env',
                        '@babel/preset-react',
                    ],
                    'plugins': [
                        '@babel/plugin-transform-react-jsx',
                        '@babel/plugin-proposal-class-properties',
                    ],
                },
            },
            ...
        ],
    },
};

My project root contains a .babelrc.json, and /my-vue-app has a babel.config.js. Additionally, there are tsconfig.json files in both project root and /my-vue-app. The versions of these modules are installed in both /package.json and /my-vue-app/package.json. Despite trying various solutions, the only working options seem messy or compromise TypeScript type checking. How can I resolve this issue in my configuration files?

Answer №1

When using the @ alias in Vue code, it must be defined in both the client and server environments. The client bundle will have it defined in the Vue CLI webpack configuration, while for the server bundle you will need to define it yourself...

webpack.server.js

const path = require('path')

module.exports = {

  resolve: {
    alias: {
      '@': path.resolve(__dirname, './vue-platform-app/src')
    },
    extensions: ['.tsx', '.ts', '.js', '.jsx', '.css', '.scss', '.sass', '.vue']
  },
}

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

Optimizing communication of time data in Laravel and Vue.js using Inertia

Currently, I am encountering an issue while working with Laravel Inertia and Vue.js. The problem arises when the time is transferred between Laravel and Vue.js, as it always converts to UTC automatically, which is not what I want. For instance, if I am u ...

Tips for including type definitions when adding elements to an array in TypeScript

Having trouble avoiding the use of 'any' as the type definition when pushing elements into an array? I attempted to specify the type but encountered an error. Here is a snippet of the code: interface answerProps { state: string; answer: s ...

Error messages encountered following the latest update to the subsequent project

Recently, I upgraded a Next project from version 12 to 14, and now I'm encountering numerous import errors when attempting to run the project locally. There are too many errors to list completely, but here are a few examples: Import trace for requeste ...

Managing errors with async/await in an Angular HttpClient function

I have been experimenting with an async/await pattern to manage a complex scenario that could potentially result in "callback hell" if approached differently. Below is a simplified version of the code. The actual implementation involves approximately 5 co ...

When utilizing the Angular 2 Stack, the Typescript Reflect.getMetadata('design:type'...) method may return an Object instead of a Date

When running the code sample below, it outputs "[Function: Date]", which is as expected. import 'reflect-metadata' function logType(target : any, key : string) { var t = Reflect.getMetadata("design:type", target, key); console.log(`${k ...

Should objects passed as props be modified in Vue.js components?

I've observed that in Vue, object fields passed as Props can be changed, and these changes reflect in the parent component. Is this considered a bad practice? Should it be avoided, or is it acceptable to use? What are the potential pitfalls of this a ...

Can you target an 'input' field that is within a component conditionally rendered using 'v-if'?

Imagine this vue.js template code: <div v-if="y===0"> <input ref="textbox">{{textbox}}</input> </div> In the scenario where y is data retrieved asynchronously, Is there a way to direct focus to the 'input' element onc ...

The Angular material slider experiences issues with functionality when paired with the *ngFor directive

Having a unique problem that I could easily replicate on stackblitz. When using multiple mat sliders generated from a *ngFor loop with numbers as values, encountering an issue where moving the first slider affects all others. Subsequent drags only update ...

Changing data in a Vue store

Using Vue 2, I have defined the data in my store as follows: export default new Vuex.Store({ state: { "cnf": { "rad": { "txf": { "minE": [1000000, 1000000], ...

What is preventing me from utilizing require in vue-router's routes.js file?

Vue-router typically requires the standard setup as outlined below: In main.js, the routes.js file is required and it usually contains code similar to this: //routes.js import Register from './components/Register' import Login from './comp ...

Leveraging the 'this' keyword in TypeScript

In my Javascript class, I used the 'this' keyword as shown below: if (this[this.props.steps[i].stepId].sendState !== undefined) { this.setState({ allStates: { ...this.state.allStates, [thi ...

Utilizing VueRouter in conjunction with Storybook: A Comprehensive Guide

I'm currently grappling with writing a narrative for a component that makes use of this.$route.params. I'm uncertain about how to artificially define this.$route within the context of a story. It seems like the answer lies in utilizing decorators ...

Encountering an Object Type Unknown error while working with Typescript and React

I am currently working on building a chatbox in React using TypeScript and Firebase. Below is the code for my Room and Message components: function ChatRoom() { const messagesRef = firestore.collection('messages'); const query = messagesRef.o ...

Angular 5: Issue with Module Resolution: Unable to locate '@angular/forms/src/validators'

Struggling to develop a unique validator using a directive, but encountering the following error: ERROR in ./src/app/CustomValidators/white-space-validator.directive.ts Module not found: Error: Can't resolve '@angular/forms/src/validators' ...

The TypeScript error code TS2339 is indicating that the 'modal' property is not recognized on the type 'JQuery'

I'm currently utilizing Typescript with AngularJS and have encountered an issue with modals when using the typed definition of jQuery library. The specific error message I am receiving is: 'error TS2339: Property 'modal' does not exist ...

Mocking store.dispatch in Jest with TypeScript did not result in any function calls being made

Testing Troubles I'm a beginner in the world of testing and I'm facing some challenges. Despite going through all the documentation on jest, I couldn't find information specific to TypeScript cases. Currently, I'm on a quest to figure ...

Using VueJs, create a dynamic css class name to be applied inline

Can VueJs handle a scenario like this? Html: <div class="someStaticClass {{someDynamicClass}}">...</div> JS: var app = new Vue({ data: { someDynamicClass: 'myClassName' }, mounted: function() { ...

The Microsoft Bing Maps V8 TypeScript library is unable to load: "Microsoft is not recognized."

I'm looking to integrate BingMaps into my React project using TypeScript. After installing the npm bingmaps package, I have included the necessary d.ts file. To import the module, I use the following code: import 'bingmaps'; Within my Com ...

Exploring an Angular Real-World Example Application on Github - Resolving the Following Bug

my surroundings. export const environment = { production: false, api_url: 'localhost:3306/api' }; my personal server is at localhost:3306 (MAMP) The instructions provided are to edit src/environments/environment.ts in order to ch ...

Exploring Angular 8 HTTP Observables within the ngOnInit Lifecycle Hook

Currently, I am still a beginner in Angular and learning Angular 8. I am in the process of creating a simple API communication service to retrieve the necessary data for display. Within my main component, there is a sub-component that also needs to fetch ...