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

ops/2024/10/18 9:22:57/

构建项目目录

在这里插入图片描述

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 需要 newmodule: {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.ppmy.cn/ops/48696.html

相关文章

Django CreateView视图

CreateView是Django提供的一个基于类的视图&#xff0c;用于处理创建新对象的操作。它可以帮助你轻松地创建一个表单页面&#xff0c;用户可以通过这个页面创建新的对象。 1&#xff0c;添加视图 Test/app3/views.py from django.shortcuts import render# Create your views…

Java 面向对象 -- Java 语言的封装、继承、多态、内部类和 Object 类

大家好&#xff0c;我是栗筝i&#xff0c;这篇文章是我的 “栗筝i 的 Java 技术栈” 专栏的第 007 篇文章&#xff0c;在 “栗筝i 的 Java 技术栈” 这个专栏中我会持续为大家更新 Java 技术相关全套技术栈内容。专栏的主要目标是已经有一定 Java 开发经验&#xff0c;并希望进…

AWS无服务器 应用程序开发—第二章AWS CodeCommit、AWS Amplify

使用AWS CodeCommit、AWS Amplify和持续部署的基本步骤 1. React.js 应用程序构建 首先,您需要使用React.js构建您的应用程序。您可以使用您喜欢的编辑器(如VS Code)来编写React.js代码,并使用Node.js和npm(或者yarn)来管理依赖项和构建过程。 2. 创建 AWS CodeCommit…

SpringBoot【2】集成 MyBatis Plus

SpringBoot 集成 MyBatis Plus 前言修改 pom.xml修改配置文件添加 实体类添加 持久层接口添加 持久层 XxxMapper.xml 文件添加 业务接口层添加 业务接口实现类添加 控制层添加 MyBatis 配置AutoFillMetaObjectHandlerMyBatisPlusConfig 验证 前言 由于 MySQL 备份/恢复测试&am…

自动控制理论---离散傅里叶变换(DFT)进行信号谱分析

1、实验设备 PC计算机1台&#xff0c;MATLAB软件1套。 2、实验目的&#xff1a; 学习使用离散傅里叶变换&#xff08;DFT&#xff09;进行信号谱分析的方法。选择合适的变换区间长度N&#xff0c;对给定信号进行谱分析&#xff0c;并绘制幅频特性和相频曲线。 3、实验原理说…

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

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

虚拟淘宝-Virtual-Taobao论文解读(AAAI2019)

目录 1 论文简介 2 文章的主要贡献 3 文章技术的简要说明 4 技术的详细说明 4.1 GAN-SD&#xff1a;生成客户特征 4.2 MAIL&#xff1a;生成交互过程 4.3 ANC&#xff1a;动规范约束 5 实验设定及结果 6 结论 7 参考 1 论文简介 南京大学LAMDA团队的侍竞成、俞扬等…

P450Rdb: CYP450数据库--地表最强系列--文献精读24

P450Rdb: A manually curated database of reactions catalyzed by cytochrome P450 enzymes P450Rdb: 一个人工整理的细胞色素P450酶催化反应数据库 http://www.cellknowledge.com.cn/p450rdb/ 还有一篇类似CYP450综述-20年-地表最强系列-文献精读-4 要点&#xff1a; P450…