【Webpack】使用 Webpack 构建 Vue3+TS 项目

news2025/2/25 15:52:02

构建项目目录

在这里插入图片描述

tsc --init
npm init -y

shim.d.ts 文件是一个类型声明文件,用于告诉 TypeScript 编译器如何处理 Vue 的单文件组件(SFC)和其他自定义模块。为 Vue 的单文件组件和其他非 TypeScript 模块提供类型信息,以便在 TypeScript 项目中使用它们时能够正确地进行类型检查和代码提示。

相关文件

App.vue

<template>
  <div>{{ x }}</div>
  <div>{{ date }}</div>
</template>
<script setup lang="ts">
import moment from "moment";

const x: number = 243
const date = moment().format("YYYY-MM-DD")
</script>
<style lang="less">
@red: red;
div {
  color: @red;
}
</style>

main.ts

import {createApp} from "vue";
import App from "./App.vue";

createApp(App).mount("#app")

shim.d.ts

// 识别 .vue 文件
declare module "*.vue" {
    import {DefineComponent} from "vue";
    const component: DefineComponent<{}, {}, any>
    export default component;
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app"></div>
</body>
</html>

安装相关依赖

webpack5 以上的版本需要安装 webpack-cli。

webpack-dev-server 开启一个本地服务。

{
  "name": "webpack-ts-vue",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack-dev-server",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^5.6.0",
    "less": "^4.2.0",
    "less-loader": "^12.2.0",
    "mini-css-extract-plugin": "^2.9.0",
    "style-loader": "^4.0.0",
    "ts-loader": "^9.5.1",
    "typescript": "^5.4.5",
    "vue-loader": "^17.4.2",
    "webpack": "^5.92.0",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^5.0.4"
  },
  "dependencies": {
    "css-loader": "^7.1.2",
    "moment": "^2.30.1",
    "vue": "^3.4.27"
  }
}

相关配置

tsconfig.json

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig to read more about this file */

    /* Projects */
    // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

    /* Language and Environment */
    "target": "es2016",
    /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    // "experimentalDecorators": true,                   /* Enable experimental support for legacy experimental decorators. */
    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
    // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
    // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */

    /* Modules */
    "module": "commonjs",
    /* Specify what module code is generated. */
    // "rootDir": "./",                                  /* Specify the root folder within your source files. */
    // "moduleResolution": "node10",                     /* Specify how TypeScript looks up a file from a given module specifier. */
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
    // "allowImportingTsExtensions": true,               /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
    // "resolvePackageJsonExports": true,                /* Use the package.json 'exports' field when resolving package imports. */
    // "resolvePackageJsonImports": true,                /* Use the package.json 'imports' field when resolving imports. */
    // "customConditions": [],                           /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
    // "resolveJsonModule": true,                        /* Enable importing .json files. */
    // "allowArbitraryExtensions": true,                 /* Enable importing files with any extension, provided a declaration file is present. */
    // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

    /* Emit */
    // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
    // "outDir": "./",                                   /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "verbatimModuleSyntax": true,                     /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,
    /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,
    /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,
    /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */
    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
    // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */
    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */

    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true
    /* Skip type checking all .d.ts files. */
  },
  //指定编译时需要包含的文件路径
  "include": [
    "src/**/*"
  ]
}

webpack.config.js

const {Configuration} = require('webpack');
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const {VueLoaderPlugin} = require("vue-loader");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

/**
 *
 * @type {Configuration} 开启配置智能提示
 */
const config = {
    mode: 'development',
    entry: './src/main.ts',
    output: {
        filename: '[chunkhash].js', // 防止命名冲突
        path: path.resolve(__dirname, 'dist'), // 生成目录
        clean: true // 每次打包前清除之前的打包目录
    },
    stats: "errors-only",  // 控制台只打印错误信息
    plugins: [
        // html 插件 使 html 文件与 webpack 关联起来
        new HtmlWebpackPlugin({
            template: './index.html'
        }),
        // 识别 vue 文件
        new VueLoaderPlugin(),
        // 分割 css 模块
        new MiniCssExtractPlugin()
    ], // webpack的插件都是 class 需要 new
    module: {
        rules: [
            // 支持 .ts 文件
            {
                test: /\.ts$/,
                // use: "ts-loader",
                use: {
                    loader: 'ts-loader',
                    // ts-loader 文档中的配置
                    options: {
                        appendTsSuffixTo: [/\.vue$/], // 支持 .vue 中的 ts 代码
                    }
                }, // 处理文件使用 loader
            },
            // 1. vue-loader 2. .vue 文件声明(shim.d.ts) 3. VueLoaderPlugin 插件配置(支持 Vue3)
            {
                test: /\.vue$/,
                use: 'vue-loader'
            },
            {
                test: /\.css$/,
                // use: ['style-loader', 'css-loader']
                use: [MiniCssExtractPlugin.loader, 'css-loader'] // 打包抽离 css 文件
            },
            {
                test: /\.less$/,
                // use: ['style-loader', 'css-loader', 'less-loader']
                use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader']
            }
        ]
    },
    // 分模块打包
    optimization: {
        splitChunks: {
            cacheGroups: {
                moment: {
                    name: "moment",
                    chunks: "all",
                    test: /[\\/]node_modules[\\/]moment[\\/]/,
                },
                // 抽离公共依赖
                common: {
                    name: "common",
                    chunks: 'all',
                    minChunks: 2, // 依赖的引用次数大于2个才会被抽离
                }
            }
        }
    }
}
module.exports = config;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1823937.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Dubbo3 服务原生支持 http 访问,兼具高性能与易用性

作者&#xff1a;刘军 作为一款 rpc 框架&#xff0c;Dubbo 的优势是后端服务的高性能的通信、面向接口的易用性&#xff0c;而它带来的弊端则是 rpc 接口的测试与前端流量接入成本较高&#xff0c;我们需要专门的工具或协议转换才能实现后端服务调用。这个现状在 Dubbo3 中得…

最新Sublime Text软件安装包分享(汉化版本)

Sublime Text 是一款广受欢迎的跨平台文本编辑器&#xff0c;专为代码、标记和散文编辑而设计。它以其简洁的用户界面、强大的功能和高性能而著称&#xff0c;深受开发者和写作者的喜爱。 一、下载地址 链接&#xff1a;https://pan.baidu.com/s/1kErSkvc7WnML7fljQZlcOg?pwdk…

[Algorithm][贪心][最长递增子序列][递增的三元子序列][最长连续递增序列][买卖股票的最佳时机][买卖股票的最佳时机Ⅱ]详细讲解

目录 1.最长递增子序列1.题目链接2.算法原理详解3.代码实现 2.递增的三元子序列1.题目链接2.算法原理详解3.题目链接 3.最长连续递增序列1.题目链接2.算法原理详解3.代码实现 4.买卖股票的最佳时机1.题目链接2.算法原理详解3.代码实现 5.买卖股票的最佳时机 II1.题目链接2.算法…

vscode cmake c++ include 设置

在这里设置编译器路径&#xff0c;include路径等等。 一个奇怪的现象是同一项目放在VS中可以cmake生成&#xff0c;并正常运行&#xff0c;但是放在VSCODE中cmake生成时会报错&#xff0c;如iostream、limits等头文件找不到。当在VS中运行执行完成调试后&#xff0c;在运行VSC…

如何解决跨境传输常见的安全及效率问题?

在当今全球化的商业版图中&#xff0c;企业为了拓展国际市场和增强竞争力&#xff0c;跨境传输数据已成为一项不可或缺的业务活动。合格的数据跨境传输方案&#xff0c;应考虑以下要素&#xff1a; 法律合规性&#xff1a;确保方案符合所有相关国家的数据保护法律和国际法规&am…

长亭培训加复习安全产品类别

下面这个很重要参加hw时要问你用的安全产品就有这个 检测类型产品 偏审计 安全防御类型 EDR类似于杀毒软件 安全评估 任何东西都要经过这个机械勘察才能上线 安全管理平台 比较杂 比较集成 审计 漏扫 评估 合在这一个平台 也有可能只是管理 主机理解为一个电脑 安了终端插件…

【java计算机专业毕设】月度员工绩效考核管理系统java MySQL springboot vue maven代码源码 送文档

1项目功能 【java计算机专业毕业设计分享】月度员工绩效考核管理系统javaweb JDK1.8,MySQL8&#xff0c;IDEA&#xff0c;Navicat java MySQL 送文档 2项目介绍 系统功能&#xff1a; 房屋租赁系统包括管理员和用户和员工俩种角色。 管理员功能涵盖了丰富的管理模块&#xff0…

使用宝塔面板 将vue+node+mysql部署至云服务器

数据库部署 1. 导出 数据库 2. 进入宝塔面板 将数据库文件导入至宝塔面板数据库中 验证是否导入成功 点击phpMyAdmin 输入用户名密码 如果没有导入成功&#xff0c;可在此再导入一遍 前端项目部署 1. 将vue项目打包上传至文件 npm run build 打包成dist文件夹 压缩上传 …

【C++11】智能指针问题

文章目录 RAII一、auto_ptr二、unique_ptr三、shared_ptrshared_ptr的循环引用问题 四、weak_ptr总结 RAII RAII就是将资源交给一个对象管理&#xff0c;这个对象能进行正常的管理和释放资源。 一、auto_ptr auto_ptr的问题是&#xff1a;在拷贝构造和赋值重载时&#xff0c…

Vue39-组件的嵌套

一、嵌套的定义 二、嵌套示例 school组件中&#xff0c;嵌套student组件 局部注册&#xff0c;注册给谁&#xff0c;就在谁的结构里面写&#xff01; vue拿不到<student>组件标签&#xff01;&#xff01;&#xff01; 三、一人之下万人之上的app组件 或者容器里面不用…

飞速(FS)InfiniBand光模块和线缆指南

InfiniBand网络架构因其高速、低延迟和可扩展性优势&#xff0c;广泛应用于高性能计算&#xff08;HPC&#xff09;。飞速&#xff08;FS&#xff09;提供多样化的InfiniBand光模块和线缆&#xff0c;为客户提供高性能InfiniBand网络解决方案&#xff0c;以建立高效可靠的网络连…

如何保护云主机安全

在数字化时代&#xff0c;云服务器已成为企业数据存储、处理和传输的重要工具。然而&#xff0c;随着其应用的广泛和深入&#xff0c;云服务器也面临着越来越多的安全威胁。为了应对这些威胁&#xff0c;白名单技术应运而生&#xff0c;成为保护云服务器安全的重要手段。 首先&…

(done) 什么是 perplexity 困惑度?

参考&#xff1a;https://www.youtube.com/watch?vB_2bntDYano 困惑度 perplexity 是一种用来衡量语言模型性能的度量&#xff0c;类似于交叉熵。 困惑度越低越好&#xff0c;越低说明一个模型越好。 一个典型的公式在下面&#xff1a;

基于机器学习的C-MAPSS涡扇发动机RUL预测

美国国家航空航天局的商用模块化航空推进仿真系统&#xff08;CMAPSS&#xff09;所模拟出的涡扇发动机性能退化数据进行实验验证&#xff0c;数据中包含有风扇、涡轮、压气机等组件参数。C-MAPSS中所包含的数据集可以模拟出从海平面到42千英尺的高度&#xff0c;从0到0.9马赫的…

前端学习CSS之神奇的块浮动

在盒子模型的基础上就可以对网页进行设计 不知道盒子模型的可以看前面关于盒子模型的内容 而普通的网页设计具有一定的原始规律,这个原始规律就是文档流 文档流 标签在网页二维平面内默认的一种排序方式,块级标签不管怎么设置都会占一行,而同一行不能放置两个块级标签 行级…

LeetCode | 434.字符串中的单词数

这道题直接使用语言内置的 split 函数可直接分离出字符串中的每个单词&#xff0c;但是要注意区分两种情况&#xff1a;1、空串&#xff1b;2、多个空格连续&#xff0c;分割后会出现空字符的情况&#xff0c;应该舍弃 class Solution(object):def countSegments(self, s):&qu…

MySQL损坏,使用data恢复数据

MySQL损坏&#xff0c;重装MySQL使用data文件恢复数据库 1.清空相关注册表(清空安装残留)2.下载合适MySQL版本(与损坏数据库版本相同)3.数据恢复4.Windows server MySQL备份bat5.设置Windows定时执行 # 初始化安装 mysqld -install# 查看数据初始化密码 mysqld --initialize --…

Commons-Collections篇-CC4链分析

前言 因为 CommonsCollections4 除 4.0 的其他版本去掉了 InvokerTransformer 继承 Serializable&#xff0c;导致该方法无法序列化。 同时 CommonsCollections 4的版本 TransformingComparator 继承了 Serializable接口&#xff0c;而CommonsCollections 3里是没有的&#xf…

183.二叉树:二叉搜索树中的众数(力扣)

代码解决 /*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* Tre…

WordPress实时搜索插件Ajax Search Lite,轻松替代默认搜索功能

WordPress自带的默认搜索功能是跳转到搜索结果页&#xff0c;如果你想要实时搜索功能&#xff0c;特别是在问答中心显示搜索功能&#xff0c;那么建议使用这个WordPress实时搜索插件Ajax Search Lite&#xff0c;它可以在文章、页面、自定义类型文章中搜索标题、内容、摘要、自…