【Vite】控制打包结构

配置 vite.config.json 文件:

import {
    
     defineConfig } from 'vite';

export default defineConfig({
    
    
    build: {
    
    
        rollupOptions: {
    
    
            output: {
    
    
                assetFileNames(chunkInfo) {
    
    
                    // css 文件
                    if (chunkInfo?.name?.endsWith('.css')) {
    
    
                        return 'styles/[name]-[hash][extname]';
                    }
                    // 图片文件
                    if (
                        ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp'].some(
                            (ext) => chunkInfo?.name?.endsWith(ext),
                        )
                    ) {
    
    
                        return 'images/[name]-[hash][extname]';
                    }
                    // 其他文件
                    return 'assets/[name]-[hash][extname]';
                },
                // 分包
                manualChunks(id) {
    
    
                    if (id.includes('node_modules')) {
    
    
                        return 'vendor';
                    }
                },
                // js 文件
                entryFileNames: 'scripts/[name]-[hash].js',
                chunkFileNames: 'scripts/[name]-[hash].js',
            },
        },
    },
});


这里我遇到一个问题,记录一下:

vite.config.json 文件在 endsWith 处抛出错误:Property ‘endsWith’ does not exist on type ‘string’. Do you need to change your target library? Try changing the ‘lib’ compiler option to ‘es2015’ or later.

打开 tsconfig.json 一看 target,是 "ES2020" 昂!奇了怪了…

仔细看看 tsconfig.json 文件,欸~ tsconfig.json 文件的最下面有一行配置:

    "references": [{
    
     "path": "./tsconfig.node.json" }]

到 tsconfig.node.json 一看,没有配置 target,默认为 "ES3"!再看一眼 include,为 ["vite.config.ts"]!回到 tsconfig.json 看一眼 include,为 ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]

噢~ 我好像懂了!tsconfig.json 为业务文件的 TS 配置文件,tsconfig.node.json 为 vite.config.ts 的 TS 配置文件!

于是我在 tsconfig.node.json 中配置 target"ES2020"

{
    
    
    "compilerOptions": {
    
    
        // 其他配置项
        "target": "ES2020" // 添加这一行
    },
    "include": ["vite.config.ts"]
}

OK!没有报错了~


猜你喜欢

转载自blog.csdn.net/Superman_H/article/details/139905550
今日推荐