nuxt / typescript

TypeScript Support for Nuxt 2
https://typescript.nuxtjs.org
MIT License
569 stars 124 forks source link

Update patch to 2.0.4 broke nuxt generate for me. #479

Open rlam3 opened 3 years ago

rlam3 commented 3 years ago

The following error was produced during nuxt-generate:

  ERROR in test/unit/Blog.spec.ts:37:24
  TS2749: 'Blog' refers to a value, but is being used as a type here. Did you mean 'typeof Blog'?
  35 |
  36 | describe('Blog', () => {
  > 37 |   let wrapper: Wrapper<Blog>
  |                        ^^^^
  38 |
  39 |   beforeEach(() => {
  40 |     wrapper = shallowMount(Blog, {

ERROR in static/sw.js:1:17
object-curly-spacing: A space is required after '{'.
  > 1 | const options = {"workboxURL":"https://cdn.jsdelivr.net/npm/workbox-cdn@5.1.4/workbox/workbox-sw.js","importScripts":[],"config":{"debug":false},"cacheOptions":{"cacheId":"XXXX-prod","directoryIndex":"/","revision":"AZ0p4cQiBFJd"},"clientsClaim":true,"skipWaiting":true,"cleanupOutdatedCaches":true,"offlineAnalytics":false,"preCaching":[{"revision":"AZ0p4cQiBFJd","url":"/?standalone=true"}],"runtimeCaching":[{"urlPattern":"/_nuxt/","handler":"CacheFirst","method":"GET","strategyPlugins":[]},{"urlPattern":"/","handler":"NetworkFirst","method":"GET","strategyPlugins":[]}],"offlinePage":null,"pagesURLPattern":"/","offlineStrategy":"NetworkFirst"}
      |                 ^
    2 |
    3 | importScripts(...[options.workboxURL, ...options.importScripts])
    4 |

 FATAL  Nuxt build error                                                                                                                            09:22:31

  at WebpackBundler.webpackCompile (node_modules/@nuxt/webpack-edge/dist/webpack.js:2128:21)
  at runMicrotasks (<anonymous>)
  at processTicksAndRejections (internal/process/task_queues.js:97:5)
  at WebpackBundler.build (node_modules/@nuxt/webpack-edge/dist/webpack.js:2077:5)
  at Builder.build (node_modules/@nuxt/builder-edge/dist/builder.js:328:5)
  at ensureBuild (node_modules/@nuxt/cli-edge/dist/cli-generate.js:145:3)
  at Object.run (node_modules/@nuxt/cli-edge/dist/cli-generate.js:281:7)
  at NuxtCommand.run (node_modules/@nuxt/cli-edge/dist/cli-index.js:413:7)

   ╭─────────────────────────────╮
   │                             │
   │   ✖ Nuxt Fatal Error        │
   │                             │
   │   Error: Nuxt build error   │
   │                             │
   ╰─────────────────────────────╯

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! XXXX@1.0.0 generate: `nuxt-ts generate`
npm ERR! Exit status 1
npm ERR!
    "@nuxt/typescript-build": "^2.0.3", WORKS
    "@nuxt/typescript-build": "^2.0.4", BREAKS

I have since rolled back to 2.0.3 without issues.

kevinmarrec commented 3 years ago

@rlam3 Your issue seems to be cause of TypeScript 4.1 update. A said in release notes, you may need to fix your type, I think that just doing what the compiler say should fix your issue.

rlam3 commented 3 years ago

@kevinmarrec I am now getting the following error when I run "nuxt-ts generate". Even with a fresh install of node_modules.

ERROR in test/unit/Blog.spec.ts:37:24
TS2344: Type '{ name: string; components: { StackedCard: { name: string; props: { data: { type: ObjectConstructor; default(): { message: string; }; }; }; data(): { currentData: () => ...; }; computed: { ...; }; methods: { ...; }; }; }; ... 5 more ...; methods: { ...; }; }' does not satisfy the constraint 'Vue'.
  Type '{ name: string; components: { StackedCard: { name: string; props: { data: { type: ObjectConstructor; default(): { message: string; }; }; }; data(): { currentData: () => ...; }; computed: { ...; }; methods: { ...; }; }; }; ... 5 more ...; methods: { ...; }; }' is missing the following properties from type 'Vue': $el, $options, $parent, $root, and 32 more.
    35 |
    36 | describe('Blog', () => {
  > 37 |   let wrapper: Wrapper<typeof Blog>
Screen Shot 2021-01-16 at 6 54 42 PM
// Blog.spec.ts

import { shallowMount, Wrapper } from '@vue/test-utils'
import Blog from '@/pages/Blog/index.vue'
import StackedCard from '@/components/cards/StackedCard.vue'

describe('Blog', () => {
  let wrapper: Wrapper<typeof Blog>

  beforeEach(() => {
    wrapper = shallowMount(Blog, {
      stubs: { StackedCard: true },
      data() {
        return {
          mediumArticles: [
            {
              title: 'ARTICLE TITLE',
              pubDate: '2019-12-31 19:12:35',
              link: '',
              guid: 'XXX',
              author: 'XXX',
            }
          ]
        }
      }
    })
  })

  afterEach(() => {
    jest.resetModules()
    jest.clearAllMocks()
  })

  it('should render articles', () => {
    wrapper.setData({
      mediumArticles: [{ id: 1 }]
    })
    // expect(axios.get).toHaveBeenCalledTimes(1)
    expect(wrapper.vm.$data.mediumArticles.length).toEqual(1)
  })

  it('renders with shallowMount and does not initialize API call', () => {
    // await wrapper.vm.$mount()

    expect(wrapper.findComponent(StackedCard).exists()).toBe(true)
    expect(wrapper.findAllComponents(StackedCard).length).toBe(1)
  })
})
// Blog/index.vue
<template>
  <div class="p-6">
    <div class="mx-auto flex flex-wrap -mx-4">
      <StackedCard
        v-for="(article, index) in filteredArticles"
        v-if="filteredArticles"
        :key="index"
        :data="article"
      />
    </div>
  </div>
</template>

<script>
import StackedCard from '~/components/cards/StackedCard.vue'

export default {
  name: 'Blog',
  components: {
    StackedCard
  },

  data() {
    return {
      mediumArticles: [],
      error: {}
    }
  },
  head() {
    return {
      title: 'Blog',
      meta: [
        {
          hid: 'XXX',
          name: 'XXX',
          content: 'XXX'
        },
      ]
    }
  },
  computed: {
    filteredArticles() {
      const articles = this.mediumArticles
      if (articles.isEmpty) {
        return null
      } else {
        return articles.filter((item) => {
          // fixing .lengthissue according to https://github.com/vuejs/vue/issues/6018
          if (
            item.categories &&
            item.categories.length > 0 &&
            item.thumbnail.includes('cdn')
          ) {
            return item
          } else {
            return null
          }
        })
      }
    },

  },

  created() {
    this.getMediumArticles()
  },
  mounted() {},

  methods: {
    async getMediumArticles() {
      const self = this

      const baseURL = 'https://api.rss2json.com/v1/api.json'
      const parameters = {
        rss_url: 'https://medium.com/feed/@XXXX'
      }

      await this.$axios
        .$get(baseURL, { params: parameters })
        .then((res) => {
          self.mediumArticles = res.items
        })
        .catch((err) => {
          this.error = err
        })
    }
  }
}
</script>

<style lang="sass" scoped></style>

Does this mean if I use typescript for my jest tests or nuxt-ts as my builder, I am required to have all files in my project to use file ".ts" extension?

Ex. I cannot have ".vue" files and use "typescript" to run my jest tests? Or are they incompatible now?

I don't remember this being an issue in the past. Would love some of your pointers on this matter. Thank you!

kevinmarrec commented 3 years ago

@rlam3 Unless you have a shims file like :

declare module '*.vue' {
  import Vue from 'vue'
  export default Vue
}

that indicates to TypeScript that your .vue files are of type Vue, it won't work cause when you're not using TypeScript in Vue files it just export an object.

That's what hapenning here.

If you're writing your test in TypeScript and want to access to a typed isntance, well types won't work as your component is JavaScript.

It may have work before cause TypeScript wasn't probably doing things well, now TypeScript shows correct errors. You can cast the wrapper type to Vue but if you want full type recogniztion without errors, your components should be typescript as well to be compliant.

vinayakkulkarni commented 3 years ago

Yep, same issue, I tried to manually add static/sw.js in exclude[] in tsconfig.json but no avail :(

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "ESNext",
    "moduleResolution": "Node",
    "lib": [
      "ESNext",
      "ESNext.AsyncIterable",
      "DOM"
    ],
    "esModuleInterop": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "noEmit": true,
    "experimentalDecorators": true,
    "baseUrl": ".",
    "paths": {
      "~/*": ["./*"],
      "@/*": ["./*"]
    },
    "types": [
      "@nuxt/types",
      "@nuxtjs/axios",
      "@types/node",
    ]
  },
  "include": ["@types/**/*"],
  "exclude": [
    "static/sw.js",
    "node_modules",
    ".nuxt",
    "dist"
  ]
}
kevinmarrec commented 3 years ago

Can someone share a reproduction repository so I can help you guys ?

rlam3 commented 3 years ago

@kevinmarrec Thank you for clarifications.

Currently, I do have the file vue-shim.d.ts in the root.

So to be clear, I now cannot use a TypeScript test testing a .vue component ? I can only have .vue components with js tests and .ts components with .ts tests correct? I cannot have a test written in ts and a component in vue? I cannot have a test written in js and a component in ts? Basically, they all have to match each other in order to work?

Also the sw.js is breaking during nuxt generate maybe due to something with the current pwa? or typescript? https://github.com/nuxt-community/pwa-module/pull/425 Or is pwa not updated to to match with this typescript module?

Thank you!

Kelmatou commented 3 years ago

@kevinmarrec I'm having the same issue, I created a repo that reproduces the error

Config typescript: 4.1.3 node: v12.16.1

What I did

As said before, 2.0.3 works, 2.0.4 breaks npm run generate

In VSCode, the error is not reported, it's only when running the nuxt command. I couldn't find the reason, maybe someone here can help

vinayakkulkarni commented 3 years ago

@kevinmarrec: This the the automated dependabot PR - https://github.com/vinayakkulkarni/map-my-google-photos/pull/104 Here's the failing build - https://app.netlify.com/sites/map-my-google-photos/deploys/6004d97518f80d00079bd740

danielroe commented 3 years ago

@vinayakkulkarni As you can see, many of the errors are from eslint, which are nothing to do with this upgrade.

I'd recommend adding sw.js to your .eslintignore.

Note also that sw.js should not be in version control, which may also be the cause of your issue.

dvelasquez commented 3 years ago

I'm getting a slightly different error. You can check the dependabot PR here: https://github.com/dvelasquez/nuxt-static-site/pull/28 and the github-action here https://github.com/dvelasquez/nuxt-static-site/pull/28/checks?check_run_id=1718622471#step:5:15

The error in question is:

ERROR in ./components/ResponsiveImage.vue
Module not found: Error: Can't resolve 'ts-loader' in 'C:\Users\d13z\dev\d13z\nuxt-static-site'
 @ ./components/ResponsiveImage.vue 2:0-67 3:0-62 3:0-62 9:2-8
 @ ./components/PlaceCard.vue
 @ ./pages/places/index.vue
 @ ./.nuxt/router.js
 @ ./.nuxt/index.js
 @ ./.nuxt/client.js
 @ multi ./node_modules/@nuxt/components/lib/installComponents.js ./.nuxt/client.js

 FATAL  Nuxt build error                                                                                                                                                  17:27:49

  at WebpackBundler.webpackCompile (node_modules\@nuxt\webpack\dist\webpack.js:5497:21)
  at processTicksAndRejections (internal/process/task_queues.js:93:5)
  at WebpackBundler.build (node_modules\@nuxt\webpack\dist\webpack.js:5446:5)
  at Builder.build (node_modules\@nuxt\builder\dist\builder.js:5634:5)
  at Object.run (node_modules\@nuxt\cli\dist\cli-build.js:109:7)
  at NuxtCommand.run (node_modules\@nuxt\cli\dist\cli-index.js:2803:7)

   ╭─────────────────────────────╮
   │                             │
   │   ✖ Nuxt Fatal Error        │
   │                             │
   │   Error: Nuxt build error   │
   │                             │
   ╰─────────────────────────────╯

error Command failed with exit code 1.
vinayakkulkarni commented 3 years ago

@vinayakkulkarni As you can see, many of the errors are from eslint, which are nothing to do with this upgrade.

I'd recommend adding sw.js to your .eslintignore.

Note also that sw.js should not be in version control, which may also be the cause of your issue.

@danielroe If you look at the static directory ( https://github.com/vinayakkulkarni/map-my-google-photos/tree/main/static ), there's no sw.js in it.

rlam3 commented 3 years ago

@kevinmarrec I'm having the same issue, I created a repo that reproduces the error

Config typescript: 4.1.3 node: v12.16.1

What I did

* npx nuxt-create-app MyApp // (include jest, typescript)

* rename Logo.spec.js into Logo.spec.ts

* added a function to mount Logo component (expliciting return type)

* add ts-shim.d.ts file at the root

* update tsconfig.json by adding @types/jest into "types", "include" and "files" sections, "resolveJsonModule" set to true

As said before, 2.0.3 works, 2.0.4 breaks npm run generate

In VSCode, the error is not reported, it's only when running the nuxt command. I couldn't find the reason, maybe someone here can help

Have you found a work around?

jcjp commented 3 years ago

I actually encountered an issue as well, when using nuxt-ts build or nuxt-ts generate. It required me to install a bunch of dependencies that are already integrated with nuxt like the following:

"@nuxt/typescript-build": "^2.0.6",
...
"@nuxtjs/robots": "^2.4.2",
"@nuxtjs/sitemap": "^2.4.0",
"@nuxtjs/stylelint-module": "^4.0.0",
"@nuxtjs/vuetify": "^1.11.3",

After adding those modules, I installed the packages using yarn install --production --silent --ignore-optional and then after I do a yarn build, I get a bunch of error in my unit test like: it, expect, etc. See below:

ERROR in pages/pageName/index.spec.ts:107:5
TS2304: Cannot find name 'expect'.
    105 |
    106 |     expect(wrapper.exists()).toBe(true)
  > 107 |     expect(...).toBeTruthy()
        |     ^^^^^^
    108 |   })
    109 |
    110 |   it('Another unit test', async() => {

ERROR in pages/pageName/index.spec.ts:110:3
TS2593: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig.
    108 |   })
    109 |
  > 110 |   it('My unit test', async() => {
        |   ^^
    111 |     create()
    112 |
    113 |     await wrapper.vm.$nextTick()

I tried downgrading the @nuxt/typescript-build exactly on version 2.0.3 and the errors for unit test files goes away, however I encountered a new error below:

ERROR in layouts/default.vue:23:5
TS2769: No overload matches this call.
  Overload 1 of 2, '(options: ComponentOptions<Vue, DefaultData<Vue>, DefaultMethods<Vue>, DefaultComputed, PropsDefinition<Record<string, any>>, Record<...>> & ThisType<...>): <VC extends VueClass<...>>(target: VC) => VC', gave the following error.
    Argument of type '{ middleware: string[]; apollo: { collection: { query: DocumentNode; variables(): { code: any; }; result({ data }: ApolloQueryResult<any>): void; }; }; }' is not assignable to parameter of type 'ComponentOptions<Vue, DefaultData<Vue>, DefaultMethods<Vue>, DefaultComputed, PropsDefinition<Record<string, any>>, Record<...>> & ThisType<...>'.
      Object literal may only specify known properties, and 'middleware' does not exist in type 'ComponentOptions<Vue, DefaultData<Vue>, DefaultMethods<Vue>, DefaultComputed, PropsDefinition<Record<string, any>>, Record<...>> & ThisType<...>'.
  Overload 2 of 2, '(target: VueClass<Vue>): VueClass<Vue>', gave the following error.
    Argument of type '{ middleware: string[]; apollo: { collection: { query: DocumentNode; variables(): { code: any; }; result({ data }: ApolloQueryResult<any>): void; }; }; }' is not assignable to parameter of type 'VueClass<Vue>'.
      Object literal may only specify known properties, and 'middleware' does not exist in type 'VueClass<Vue>'.
    21 |
    22 |   @Component({
  > 23 |     middleware: ['middleware-1', 'middleware-2'],
       |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    24 |
    25 |     apollo: {
    26 |       collection: {

 FATAL  Nuxt build error                                                                                                           19:07:26  

  at WebpackBundler.webpackCompile (node_modules/@nuxt/webpack/dist/webpack.js:2125:21)
  at runMicrotasks (<anonymous>)
  at processTicksAndRejections (internal/process/task_queues.js:93:5)
  at async WebpackBundler.build (node_modules/@nuxt/webpack/dist/webpack.js:2074:5)
  at async Builder.build (node_modules/@nuxt/builder/dist/builder.js:327:5)
  at async Object.run (node_modules/@nuxt/cli/dist/cli-build.js:110:7)
  at async NuxtCommand.run (node_modules/@nuxt/cli/dist/cli-index.js:413:7)

   ╭─────────────────────────────╮
   │                             │
   │   ✖ Nuxt Fatal Error        │
   │                             │
   │   Error: Nuxt build error   │
   │                             │
   ╰─────────────────────────────╯

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I change some of the data in the error for privacy purposes.

vinayakkulkarni commented 3 years ago

I've found a solution, the issue was caused due to typeCheck enabled in nuxt.config.ts as directed here in the docs - https://typescript.nuxtjs.org/guide/lint/#runtime-lint

The solution was to send in array of files/directories which typescript will check in runtime.

-  typescript: {
-    typeCheck: {
-      eslint: {
-        enabled: true,
-        files: './**/*.{ts,js,vue}',
-      },
-    },
-  },
+  typescript: {
+    typeCheck: {
+      eslint: {
+        enabled: true,
+        files: [
+          'assets/**/*.{ts,js}',
+          'components/**/*.{ts,js,vue}',
+          'layouts/**/*.{ts,js,vue}',
+          'pages/**/*.{ts,js,vue}',
+          'plugins/**/*.{ts,js}',
+          'shims/**/*.{ts,js}',
+        ],
+      },
+    },
+  },
yshrsmz commented 3 years ago

I've workaround the issue by ignoring some files.

  typescript: {
    typeCheck: {
      eslint: {
        files: './**/*.{ts,js,vue}',
        options: {
          ignorePattern: ['./components/**/*.spec.ts'],
        },
      },
    },
  },

In my case Nuxt only complains about types in test cases, so this was enough. It's just a variant of the solution from @vinayakkulkarni, thanks!

There should be a proper fix, though.

danielroe commented 3 years ago

You should add "jest" to your types array in tsconfig.json. And you may need to install @types/jest too.

yshrsmz commented 3 years ago

You should add "jest" to your types array in tsconfig.json. And you may need to install @types/jest too.

I already have these configurations and vue-shim.d.ts.

Say I have codes like below, and these work fine when I use the older version of @nuxt/typescript-build.

<script lang="ts">
import Vue from 'vue'

export default Vue.extend({...})
</script>
import { Wrapper } from '@vue/test-utils'
import SomeComponent from '~/components/SomeComponent.vue'

let wrapper: Wrapper<SomeComponent>

When I build with @nuxt/typescript-build v2.1.0, it says

'SomeComponent' refers to a value, but is being used as a type here. Did you mean 'typeof SomeComponent'?

So I changed like below

import { Wrapper } from '@vue/test-utils'
import SomeComponent from '~/components/SomeComponent.vue'

let wrapper: Wrapper<typeof SomeComponent>

then it says

Type 'ExtendedVue<Vue, unknown, unknown, unknown, Record<never, any>>' does not satisfy the constraint 'Vue'.
  Type 'VueConstructor<Record<never, any> & Vue>' is missing the following properties from type 'Vue': $el, $options, $parent, $root, and 33 more.

So I may be wrong, but it looks like Nuxt's runtime type check can see the actual type of Single File Components, and that type is different from what @vue/test-utils expects.

So maybe it's a type definition bug in @vue/test-utils 🤔 Or we need to update vue-shim.d.ts to something that more precisely conforms to the actual type?

rlam3 commented 3 years ago

You should add "jest" to your types array in tsconfig.json. And you may need to install @types/jest too.

@danielroe

Could you please provide us a brand new repo example? I'm confused by what you mean by adding "jest" to your types array in tsconfig. Right now we don't have any definitive answers and this seems like a recurring challenge for those whom were using older versions from 2.0.4 and trying to upgrade to the latest patches. Minor patches I believe should ideally be backwards compatible. Thank you.

jcjp commented 3 years ago

I've workaround the issue by ignoring some files.

  typescript: {
    typeCheck: {
      eslint: {
        files: './**/*.{ts,js,vue}',
        options: {
          ignorePattern: ['./components/**/*.spec.ts'],
        },
      },
    },
  },

In my case Nuxt only complains about types in test cases, so this was enough. It's just a variant of the solution from @vinayakkulkarni, thanks!

There should be a proper fix, though.

This actually fixed my issue.

akadlec commented 3 years ago

hi to all. since version 2.0.4 I have issues when Nuxt is rebuilding after changes. Client build freeze at about 90% so I have to kill dev server and start it again.

mirkopoloni commented 3 years ago

Hey @akadlec did you solve your problem? I had the same issue today and the way to fix it was to only import the files that need to be checked from eslint. e.g.

typescript: {
    typeCheck: {
      eslint: {
        files: './**/*.{ts,js,vue}',
      },
    },
  },

This was freezing the client build because somehow eslint couldn't load some config files inside the node_modules folder.

The solution for me was to include only specific files, like this:

 typescript: {
    typeCheck: {
      eslint: {
        files: [
          './src/**/*.{ts,js,vue}',
          './cypress/**/*.{ts,js,vue}',
          './*.{ts,js,vue}',
        ],
      },
    },
  }

Try to import only the files you need, it obviously depends on how your project's folder structure look like.

akadlec commented 3 years ago

Hi @mirkopoloni i have fixed it by complete upgrading of all libs which I'm using