webpack构建vue3+ts项目

使用webpack、webpack-cli 自定义构建vue3项目

  1. 初始化项目目录

webpack构建vue3+ts项目_第1张图片

  1. 使用pnpm安装 项目依赖

webpack、webpack-cli

pnpm add -D xxx

{
    "name": "webpack-cli-vue3-ts",
    "version": "1.0.0",
    "description": "webpack-cli-vue3-ts",
    "main": "webpack.config.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "dev": "webpack-dev-server",
        "build": "webpack"
    },
    "author": "",
    "license": "ISC",
    "dependencies": {
        "vue": "^3.2.46"
    },
    "devDependencies": {
        "clean-webpack-plugin": "^4.0.0",
        "css-loader": "^6.7.3",
        "friendly-errors-webpack-plugin": "^1.7.0",
        "html-webpack-plugin": "^5.5.0",
        "less": "^4.1.3",
        "less-loader": "^11.1.0",
        "style-loader": "^3.3.1",
        "ts-loader": "^9.4.2",
        "typescript": "^4.9.5",
        "vue-compiler-sfc": "^0.0.0",
        "vue-loader": "^17.0.1",
        "webpack": "^5.75.0",
        "webpack-cli": "^5.0.1",
        "webpack-dev-server": "^4.11.1"
    }
}
  1. 配置ts , tsc --init 生成ts 文件 如果没有tsc 安装npm install typescript -g

{
    "include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
    "exclude": ["node_modules"],
    "compilerOptions": {
        /* Basic Options */
        // "incremental": true,                   /* Enable incremental compilation */
        "target": "esnext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
        "module": "esnext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
        "lib": [
            "esnext",
            "dom",
            "dom.iterable",
            "scripthost"
        ] /* Specify library files to be included in the compilation. */,
        // "allowJs": true,                       /* Allow javascript files to be compiled. */
        // "checkJs": true,                       /* Report errors in .js files. */
        "jsx": "preserve" /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */,
        // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
        // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
        "sourceMap": true /* Generates corresponding '.map' file. */,
        // "outFile": "./",                       /* Concatenate and emit output to single file. */
        // "outDir": "./",                        /* Redirect output structure to the directory. */
        // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
        // "composite": true,                     /* Enable project compilation */
        // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
        // "removeComments": true,                /* Do not emit comments to output. */
        // "noEmit": true,                        /* Do not emit outputs. */
         //noEmitOnError": true,                  /* Do not emit outputs. */
        "importHelpers": true /* Import emit helpers from 'tslib'. */,
        // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
        // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

        /* Strict Type-Checking Options */
        "strict": true /* Enable all strict type-checking options. */,
        "noImplicitAny": false /* Raise error on expressions and declarations with an implied 'any' type. */,
        // "strictNullChecks": true,              /* Enable strict null checks. */
        // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
        // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
        // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
        // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
        // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

        /* Additional Checks */
        // "noUnusedLocals": true,                /* Report errors on unused locals. */
        // "noUnusedParameters": true,            /* Report errors on unused parameters. */
        // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
        // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

        /* Module Resolution Options */
        "moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
        "skipLibCheck": true,
        "allowSyntheticDefaultImports": true,
        "baseUrl": "./" /* Base directory to resolve non-absolute module names. */,
        "paths": {
            "@/*": ["src/*"]
        } /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */,
        // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
        // "typeRoots": [],                       /* List of folders to include type definitions from. */
        // "types": [],                           /* Type declaration files to be included in compilation. */
        // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
        "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
        // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
        // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

        /* Source Map Options */
        // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
        // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
        // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
        // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

        /* Experimental Options */
        // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
        // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

        /* Advanced Options */
        "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
    },
    "references": [
        {
            "path": "./tsconfig.config.json"
        }
    ]
}
  1. 配置 ts支持vue的申明文件env.d.ts

declare module '*.vue' {
    import { DefineComponent } from 'vue'
    const component: DefineComponent<{}, {}, any>
    export default component
}
  1. 配置webpack.config.js

const { Configuration } = require('webpack')
const path = require('path')
const htmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const { VueLoaderPlugin } = require('vue-loader/dist/index')

const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')

/**
 * @type {Configuration} // 配置webpack提示
 */
const config = {
    mode: 'development',
    entry: './src/main.ts',
    output: {
        filename: '[hash].js',
        path: path.resolve(__dirname, 'dist'),
    },
    resolve: {
        alias: {
            '@': path.resolve(__dirname, 'src'),
        },
        extensions: ['.vue', '.ts', '.js'],
    },
    module: {
        // 允许你在 webpack 配置中指定多个 loader(loader 用于对模块的源代码进行转换)
        rules: [
            {
                test: /\.vue$/, // 解析vue文件
                use: 'vue-loader',
            },
            {
                test: /\.css$/, // 解析css文件
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /\.less$/, // 解析less文件
                use: ['style-loader', 'css-loader', 'less-loader'],// 有执行顺序,从右往左 先执行 less-loader --> css-loader-->style-loader
            },
            {
                test: /\.ts/, //解析ts
                loader: 'ts-loader',
                options: {
                    configFile: path.resolve(process.cwd(), 'tsconfig.json'),
                    appendTsSuffixTo: [/\.vue$/],
                },
            },
        ],
    },
    stats: 'errors-only', //取消提示
    devServer: {
        port: 8088,
    },
    plugins: [
        new htmlWebpackPlugin({
            template: './public/index.html', //解析 html模板
        }),
        new VueLoaderPlugin(), // 解析vue
        new CleanWebpackPlugin(), // 清空dist目录重新生成打包文件起到美化的作用
        new FriendlyErrorsWebpackPlugin({
            compilationSuccessInfo: {
                // 美化webpack工作台输出日志
                messages: [
                    'You application is running here http://localhost:8088',
                ],
            },
        }),
    ],
    externals: {
        vue: ['Vue'], // CDN引入
    },
}

module.exports = config
  1. 项目vue使用cdn方式引入

---webpack.config.js
module.exports = {
  externals: {
        vue: ['Vue'], // CDN引入
    },
}
---public/index.html




    
    
    
    webpack vue3-ts-demo
    



    
cdn 引入的优势:
通过减少用户和内容之间的地理距离,减轻源服务器的访客压力,将访客的请求发送到不同的缓存服务器中,加快访问速度,提高响应时间。这是CDN的主要优势。
减轻源服务器的访客压力,将访客的请求发送到不同的缓存服务器中,不仅加快了访问速度,而且也可以有效的抵抗DDOS攻击
CDN的好处还包括提高站点可靠性,因为如果一台服务器出现故障,流量可以重新路由到CDN网络中的另一台服务器。
CDN提供的安全优势有助于抵御DDoS攻击,并确保针对单个服务器的攻击不会导致整个应用程序崩溃。
cdn劣势:
CDN的两个主要缺点是成本和管理开销
使用外部cdn若网络环境差的情况下或cdn资源有问题,会导致网页白屏时间长,影响用户体验
  1. 项目效果

webpack构建vue3+ts项目_第2张图片
webpack构建vue3+ts项目_第3张图片

你可能感兴趣的:(webpack,vue)