2

我设置了一个小型 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

项目的文件夹结构

=======

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$/] }
      },
    ],
  },
}

应用程序.js

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

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

app.$mount('#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
}

包.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"
  }
}
4

0 回答 0