Reputation: 1302
TL;DR: How can I import and use a typescript module into my plain js Vue-Components?
I have a Vue 2 (not yet 3) project. In this project I've moved some logic to es modules for better testability and to make them more reusable. Something like this:
export const getHistory = () => {
// ...
}
In a plain JS Vue-Component I would then import {getHistory} from '../modules/listHistory'
that function and use it in combination with some presentation logic.
Now, I would like to move this function to a typescript module like this:
interface ListHistory {
id: number;
}
export function getHistory(): ListHistory[] {
// ...
}
I (naively) assumed I could just continue importing the function and use it in the same way as before in my JS-Components. However, that doesn't work and fails with this error message:
These relative modules were not found:
* ../../modules/listHistory in ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/quick-actions/quick-actions.vue?vue&type=script&lang=js&
Following the vue guidelines on typescript I've added a tsconfig.json
file to my project:
{
"compilerOptions": {
"target": "es5",
"strict": true,
"module": "es2015",
"moduleResolution": "node"
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
]
}
I've also added typescript
as a dev dependency to my project.
While searching around for a solution I could only find people trying to import plain-js modules in typescript projects, nothing like the thing I want to do.
I know that importing Typescript stuff into plain JS code doesn't give you all the advantages of Typescript but since I will migrate the whole thing to VueJS 3 at some point and I do want to use types, I better start now by moving stuff that can already be moved to typescript.
Upvotes: 3
Views: 457
Reputation: 37793
Installing TS and adding tsconfig.json
config file to a Vue project based on Vue CLI/Webpack is not enough as you also need to configure Webpack to correctly handle TS files or <script lang='ts'>
blocks in Vue SFCs (using ts-loader)
Easiest way to start using TS in a project managed by Vue CLI is using the CLI plugin @vue/cli-plugin-typescript
vue add typescript
Upvotes: 3