为什么我在 webpack-dev-server 重新编译时收到“找不到模块...”的“.vue”文件的打字稿错误?

问题描述

我设置了一个小型 webpack 项目,该项目创建了一个 Vue 应用程序包,该包包含在注入应用程序的静态 HTML 文件中。我想用 Typescript 编写组件,所以我在 webapck 配置中包含了 ts-loader。构建过程 - 使用“webpack”命令 - 工作正常,但我在使用 webpack-dev-server 时遇到了一些问题。

当我最初启动服务器时,一切正常:在我的本地服务器上创建并提供包,浏览器正确显示应用程序。但是,当我更改源代码并保存时,重新编译代码时出现 Typescript 错误,告诉我组件的“.vue”文件缺少模块或声明:

TS2307: Cannot find module './components/Banner.vue' or its corresponding type declarations.

要启动服务器,我使用以下命令:

webpack serve --open

Project's folder structure

========

webpack.config.js

const { VueLoaderPlugin } = require('vue-loader')
const path = require('path')

module.exports = {
  mode: 'development',devtool: 'inline-source-map',entry: {
    app: './src/app.js',},output: {
    filename: '[name].bundle.js',plugins: [
    new VueLoaderPlugin(),],devServer: {
    contentBase: path.join(__dirname,'dist'),module: {
    rules: [
      {
        test: /\.vue$/,use: ['vue-loader']
      },{
        test: /\.ts$/,loader: 'ts-loader',exclude: [/node_modules/],options: { appendTsSuffixTo: [/\.vue$/] }
      },}

app.js

import Vue from 'vue'
import App from './App.vue'

const app = new Vue({
  render: (h) => h(App)
})

app.$mount('#app')

App.vue

<template>
  <div id="app">
    <h1>{{ welcomeMessage }}</h1>
    <Banner />
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import Banner from './components/Banner.vue'

export default Vue.extend({
  components: {
    Banner,data: () => ({
    welcomeMessage: 'Hello World!'
  })
})
</script>

tsconfig.json

{
  "compilerOptions": {
    "target": "es5","strict": true,"module": "es2015","moduleResolution": "node"
  }
}

@types/vue-shims.d.ts

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

package.json

{
  "name": "2021-06-21-webpack","version": "1.0.0","description": "","main": "index.js","scripts": {
    "build": "webpack","dev": "webpack serve --open"
  },"keywords": [],"author": "","license": "ISC","devDependencies": {
    "ts-loader": "^8.3.0","typescript": "^4.3.4","vue-loader": "^15.9.7","vue-template-compiler": "^2.6.14","webpack": "^4.46.0","webpack-cli": "^4.7.2","webpack-dev-server": "^3.11.2"
  },"dependencies": {
    "vue": "^2.6.14"
  }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)