TypeScript路径别名-如何解决导入错误

时间:2019-04-30 12:58:48

标签: typescript vue.js vue-cli-3

我使用Vue CLI 3生成了Vue.js项目,并使用@别名编写了import语句。执行npm run build时,发生导入错误。为什么?

错误消息

$ npm run build

> vuejs-exercises@0.1.0 build /Users/???/Desktop/example
> vue-cli-service build


⠙  Building for production...Starting type checking and linting service...
Using 1 worker with 2048MB memory limit
⠼  Building for production...

 ERROR  Failed to compile with 1 errors                                                                                 21:07:57

This dependency was not found:

* @/models/Member in ./node_modules/cache-loader/dist/cjs.js??ref--13-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/
babel-loader/lib!./node_modules/ts-loader??ref--13-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader
/lib??vue-loader-options!./src/main/javascript/components/Vote.vue?vue&type=script&lang=ts&

To install it, you can run: npm install --save @/models/Member
 ERROR  Build failed with errors.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! vuejs-exercises@0.1.0 build: `vue-cli-service build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the vuejs-exercises@0.1.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/???/.npm/_logs/2019-04-30T12_07_57_611Z-debug.log

文件

tsconfig.json

    "paths": {
      "@/*": [
        "src/main/javascript/*",
        "src/test/javascript/*"
      ]
    },

src / main / javascript / models / Member.ts

export default class Member {
 ...
}

src / main / javascript / components / Vote.vue

import Member from '@/models/Member'; // import error

源代码:https://github.com/yoshikit1996/vuejs-exercise

语法突出显示

我的VSCode可以检测到导入错误,但是没有使用@别名检测到它。 vscode highlight vscode error highlith

1 个答案:

答案 0 :(得分:1)

您可以在vue.config.js中使用configureWebpackchainWebpack来设置自己的别名

vue.config.js

const path = require('path')
module.exports = {
  chainWebpack: config => {
        config.resolve.alias
        .set('@', path.resolve(__dirname, 'src/main/javascript'));
  }
}