带有 webpack 别名的 Vue-typescript 错误,找不到路径 [英] Vue-typescript error with webpack alias, path not found

查看:36
本文介绍了带有 webpack 别名的 Vue-typescript 错误,找不到路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 typescript 的 vue 项目上配置 webpack 别名时遇到问题.如果我使用普通的 javascript,则不会遇到同样的问题,因此我很困惑

I have a problem configuring webpack alias on a vue project with typescript. The same issue is not faced if I'm using normal javascript, hence my confusion

该项目分为 2 个,app_marketplace"、app_producer"(类似于管理员),我还有一个用于共享组件和实用程序的第三个文件夹.

The project is divided in 2, "app_marketplace", "app_producer" (which is like the admin), I also have a 3rd folder for shared components and utilities.

项目文件夹结构:

  • .env.marketplace
  • .env.producer
  • 公开/
  • 源代码/
    • app_marketplace/
    • app_producer/
    • app_shared/

    我与 package.json 中的脚本分开运行 2 应用程序.

    I run the 2 app separately from the script in the package.json.

    例如,"serve:marketplace": "vue-cli-service serve --mode market src/app_marketplace/main.ts" 调用我的 .env.marketplace 文件并将 env 设置为 VUE_APP_MARKETPLACE=true

    For instance, "serve:marketplace": "vue-cli-service serve --mode marketplace src/app_marketplace/main.ts" calls my .env.marketplace file and sets the env to VUE_APP_MARKETPLACE=true

    现在,在我的 vue.config.js 中,我正在使用 env 变量来设置别名.

    Now, in my vue.config.js I'm making use of the env variable to set the aliases.

    configureWebpack: {
        resolve: {
            alias: {
                '~': path.resolve(__dirname, 'src/app_shared'),
                '@': path.resolve(__dirname, process.env.VUE_APP_MARKETPLACE ? 'src/app_marketplace' : 'src/app_producer')
            }
        }
    }
    

    问题是从 app_marketplace 中的 main.ts 开始,很多导入不起作用或给我错误.我无法解释的另一件事是为什么其中一些有效而一些无效.

    The problem is that a lot of the imports don't work or give me error, starting from my main.ts inside app_marketplace. Another thing I can't explain is why some of them work and some don't.

    import App from './App.vue'
    import router from '~/router' // ERROR
    import store from '@/store' // ERROR
    import '@/plugins'
    import '~/directives'
    import { DEBUG } from '~/const/debug' // ERROR
    

    我做错了什么?

    推荐答案

    你的 tsconfig.json 应该有一个与你的 Webpack 路径别名匹配的 paths 配置:

    Your tsconfig.json should have a paths config that matches your Webpack path aliases:

    {
      "paths": {
        "~/*": [
          "src/app_shared/*",
        ],
        "@/*": [
          "src/*"
        ]
      },
      ...
    }
    

    由于文件是 JSON,您将无法在文件中设置条件路径别名.

    Since the file is JSON, you won't be able to do conditional path aliases in the file.

    这篇关于带有 webpack 别名的 Vue-typescript 错误,找不到路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆