z0ffy / vite-plugin-bundle-obfuscator

JavaScript obfuscator plugin for Vite, offering customizable options and multi-threading support to strengthen code security.
https://github.com/z0ffy/vite-plugin-bundle-obfuscator
MIT License
37 stars 0 forks source link

error during build: [vite:build-html] __dirname is not defined #64

Closed 3517283258 closed 1 day ago

3517283258 commented 1 day ago

build报错:

ERROR  error during build:                                                                                                                           20:30:50  
[vite:build-html] __dirname is not defined
    at file:///E:/vue-projects/schisandra-cloud-album-front/node_modules/vite-plugin-bundle-obfuscator/dist/index.mjs:1:1867
    at new Promise (<anonymous>)
    at A (file:///E:/vue-projects/schisandra-cloud-album-front/node_modules/vite-plugin-bundle-obfuscator/dist/index.mjs:1:1828)
    at n (file:///E:/vue-projects/schisandra-cloud-album-front/node_modules/vite-plugin-bundle-obfuscator/dist/index.mjs:1:4016)
    at applyHtmlTransforms (file:///E:/vue-projects/schisandra-cloud-album-front/node_modules/vite/dist/node/chunks/dep-Cyk9bIUq.js:35874:23)
    at Object.generateBundle (file:///E:/vue-projects/schisandra-cloud-album-front/node_modules/vite/dist/node/chunks/dep-Cyk9bIUq.js:35614:24)
    at file:///E:/vue-projects/schisandra-cloud-album-front/node_modules/rollup/dist/es/shared/node-entry.js:19913:40

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

屏幕截图 2024-10-21 192815

环境: node: v20.16.0

package.json:

  "dependencies": {
    "@alova/adapter-axios": "^2.0.8",
    "@ant-design/icons-vue": "^7.0.1",
    "@tensorflow/tfjs": "^4.21.0",
    "@types/animejs": "^3.1.12",
    "@types/crypto-js": "^4.2.2",
    "@types/json-stringify-safe": "^5.0.3",
    "@types/node": "^22.7.5",
    "@types/nprogress": "^0.2.3",
    "@vueuse/core": "^11.1.0",
    "alova": "^3.1.0",
    "animejs": "^3.2.2",
    "ant-design-vue": "^4.2.5",
    "axios": "^1.7.7",
    "browser-image-compression": "^2.0.2",
    "buffer": "^6.0.3",
    "crypto-js": "^4.2.0",
    "eslint": "9.12.0",
    "go-captcha-vue": "^2",
    "json-stringify-safe": "^5.0.1",
    "less": "^4.2.0",
    "localforage": "^1.10.0",
    "nprogress": "^0.2.0",
    "nsfwjs": "^4.2.0",
    "pinia": "^2.2.4",
    "pinia-plugin-persistedstate": "^4.1.1",
    "seedrandom": "^3.0.5",
    "unplugin-auto-import": "^0.18.3",
    "vite-plugin-compression": "^0.5.1",
    "vite-plugin-html": "^3.2.2",
    "vite-plugin-node-polyfills": "^0.22.0",
    "vue": "^3.5.12",
    "vue-dompurify-html": "^5.1.0",
    "vue-i18n": "^10.0.4",
    "vue-router": "^4.4.5",
    "ws": "^8.18.0"
  },
  "devDependencies": {
    "@eslint/js": "^9.12.0",
    "@vitejs/plugin-vue": "^5.1.4",
    "eslint-plugin-vue": "^9.29.0",
    "globals": "^15.11.0",
    "sass": "^1.79.5",
    "typescript": "^5.6.3",
    "typescript-eslint": "^8.9.0",
    "unplugin-vue-components": "^0.27.4",
    "vite": "^5.4.9",
    "vite-plugin-bundle-obfuscator": "^1.2.0",
    "vite-plugin-chunk-split": "^0.5.0",
    "vue-tsc": "^2.1.6"
  }

插件配置:

const defaultObfuscatorConfig:any = {
    excludes: [],
    enable: true,
    log: true,
    autoExcludeNodeModules: false,
    threadPool: {
        size: 4,
        enable: true,
    },
    options: {
        compact: true,
        controlFlowFlattening: true,
        controlFlowFlatteningThreshold: 1,
        deadCodeInjection: false,
        debugProtection: false,
        debugProtectionInterval: 0,
        disableConsoleOutput: false,
        identifierNamesGenerator: 'hexadecimal',
        log: false,
        numbersToExpressions: false,
        renameGlobals: false,
        selfDefending: true,
        simplify: true,
        splitStrings: false,
        stringArray: false,
        stringArrayCallsTransform: false,
        stringArrayCallsTransformThreshold: 0.5,
        stringArrayEncoding: [],
        stringArrayIndexShift: true,
        stringArrayRotate: true,
        stringArrayShuffle: true,
        stringArrayWrappersCount: 1,
        stringArrayWrappersChainedCalls: true,
        stringArrayWrappersParametersMaxCount: 2,
        stringArrayWrappersType: 'variable',
        stringArrayThreshold: 0.75,
        unicodeEscapeSequence: false,
    }
};
3517283258 commented 1 day ago

测试发现好像是添加配置threadPool 导致的:

threadPool: {
        size: 4,
        enable: true,
    },

设置成false ,就没问题了,不知道为啥

z0ffy commented 1 day ago

测试发现好像是添加配置threadPool 导致的:

threadPool: {
        size: 4,
        enable: true,
    },

设置成false ,就没问题了,不知道为啥

看下怎么引入的

3517283258 commented 1 day ago

测试发现好像是添加配置threadPool 导致的:

threadPool: {
        size: 4,
        enable: true,
    },

设置成false ,就没问题了,不知道为啥

看下怎么引入的

import {defineConfig, loadEnv} from 'vite';
import vue from '@vitejs/plugin-vue';
import * as path from 'path';
import viteCompression from "vite-plugin-compression";
import {createHtmlPlugin} from "vite-plugin-html";
import {nodePolyfills} from "vite-plugin-node-polyfills";
import Components from 'unplugin-vue-components/vite';
import {AntDesignVueResolver} from 'unplugin-vue-components/resolvers';
import AutoImport from 'unplugin-auto-import/vite';
import {chunkSplitPlugin} from 'vite-plugin-chunk-split';
import vitePluginBundleObfuscator from 'vite-plugin-bundle-obfuscator';

const defaultObfuscatorConfig: any = {
    excludes: [],
    enable: true,
    log: true,
    autoExcludeNodeModules: false,
    threadPool: false,
    options: {
        compact: true,
        controlFlowFlattening: true,
        controlFlowFlatteningThreshold: 1,
        deadCodeInjection: false,
        debugProtection: false,
        debugProtectionInterval: 0,
        disableConsoleOutput: false,
        identifierNamesGenerator: 'hexadecimal',
        log: false,
        numbersToExpressions: false,
        renameGlobals: false,
        selfDefending: true,
        simplify: true,
        splitStrings: false,
        stringArray: false,
        stringArrayCallsTransform: false,
        stringArrayCallsTransformThreshold: 0.5,
        stringArrayEncoding: [],
        stringArrayIndexShift: true,
        stringArrayRotate: true,
        stringArrayShuffle: true,
        stringArrayWrappersCount: 1,
        stringArrayWrappersChainedCalls: true,
        stringArrayWrappersParametersMaxCount: 2,
        stringArrayWrappersType: 'variable',
        stringArrayThreshold: 0.75,
        unicodeEscapeSequence: false,
    }
};
export default defineConfig(({mode}: { mode: string }): object => {
        const env: Record<string, string> = loadEnv(mode, process.cwd());
        return {
            publicDir: 'public',
            base: '/',
            resolve: {
                //设置别名
                alias: {
                    '@': path.resolve(__dirname, 'src')
                }
            },
            plugins: [
                vue(),
                vitePluginBundleObfuscator(defaultObfuscatorConfig),
                chunkSplitPlugin({
                    strategy: "default",
                    useEntryName: true,
                }),
                Components({
                    dts: true,
                    dirs: ['src/components', 'src/views'],
                    resolvers: [
                        AntDesignVueResolver({
                            importStyle: false,
                            resolveIcons: true
                        }),
                    ],
                }),
                AutoImport({

                    imports: ['vue', 'vue-router', 'pinia', '@vueuse/core'],
                    dts: 'auto-import.d.ts',
                    //ant-design-vue
                    resolvers: [AntDesignVueResolver({
                        importStyle: false,
                        resolveIcons: true
                    })],
                    eslintrc: {
                        enabled: false // 1、改为true用于生成eslint配置。2、生成后改回false,避免重复生成消耗
                    }
                }),
                nodePolyfills(),
                viteCompression({
                    filter: /\.(js|mjs|css|html)$/i, 
                    verbose: true,
                    disable: false,
                    threshold: 10240, 
                    algorithm: "gzip", 
                    ext: ".gz",
                    deleteOriginFile: true, 
                }),
                createHtmlPlugin({
                    minify: true,
                    /**
                     * 在这里写entry后,你将不需要在`index.html`内添加 script 标签,原有标签需要删除
                     * @default src/main.ts
                     */
                    entry: "src/main.ts",
                    /**
                     * 如果你想将 `index.html`存放在指定文件夹,可以修改它,否则不需要配置
                     * @default index.html
                     */
                    template: "index.html",
                    /**
                     * 需要注入 index.html ejs 模版的数据
                     */
                    inject: {
                        data: {
                            title: env.VITE_TITLE_NAME,
                        },
                    },
                }),
            ],
            css: {
                preprocessorOptions: {
                    scss: {
                        api: "modern-compiler",
                        javascriptEnabled: true,
                    },
                    less: {
                        javascriptEnabled: true,
                    },
                },
                modules: {

                    generateScopedName: "[name]__[local]___[hash:base64:5]",
                },

            },

            esbuild: {
                drop: env.VITE_NODE_ENV === 'production' ? ['console', 'debugger'] : [],
            },
            build: {
                outDir: "dist", // 指定输出路径
                assetsDir: "assets", // 指定生成静态文件目录
                assetsInlineLimit: "4096", // 小于此阈值的导入或引用资源将内联为 base64 编码
                cssCodeSplit: true, // 启用 CSS 代码拆分
                sourcemap: false, // 构建后是否生成 source map 文件
                minify: "esbuild", // 指定使用哪种混淆器
                write: true, // 启用将构建后的文件写入磁盘
                emptyOutDir: true, // 构建时清空该目录
                brotliSize: true, // 启用 brotli 压缩大小报告
                chunkSizeWarningLimit: 6000, // chunk 大小警告的限制
                watch: null, // 设置为 {} 则会启用 rollup 的监听器
                rollupOptions: {  // 自定义底层的 Rollup 打包配置
                    output: {
                        chunkFileNames: 'js/[name]-[hash].js', // 引入文件名的名称
                        entryFileNames: 'js/[name]-[hash].js', // 包的入口文件名称
                        assetFileNames: '[ext]/[name]-[hash].[ext]',// 资源文件像 字体,图片等
                    },
                }
            },
            server: {
                proxy: {
                    [env.VITE_APP_BASE_API]: {

                        target: env.VITE_API_BASE_URL,

                        changeOrigin: true,
                        rewrite: (path: string) => path.replace(RegExp(`^${env.VITE_APP_BASE_API}`), ""),
                    },
                },
            },
        };
    }
)
;
z0ffy commented 1 day ago

测试发现好像是添加配置threadPool 导致的:

threadPool: {
        size: 4,
        enable: true,
    },

设置成false ,就没问题了,不知道为啥

看下怎么引入的

import {defineConfig, loadEnv} from 'vite';
import vue from '@vitejs/plugin-vue';
import * as path from 'path';
import viteCompression from "vite-plugin-compression";
import {createHtmlPlugin} from "vite-plugin-html";
import {nodePolyfills} from "vite-plugin-node-polyfills";
import Components from 'unplugin-vue-components/vite';
import {AntDesignVueResolver} from 'unplugin-vue-components/resolvers';
import AutoImport from 'unplugin-auto-import/vite';
import {chunkSplitPlugin} from 'vite-plugin-chunk-split';
import vitePluginBundleObfuscator from 'vite-plugin-bundle-obfuscator';

const defaultObfuscatorConfig: any = {
    excludes: [],
    enable: true,
    log: true,
    autoExcludeNodeModules: false,
    threadPool: false,
    options: {
        compact: true,
        controlFlowFlattening: true,
        controlFlowFlatteningThreshold: 1,
        deadCodeInjection: false,
        debugProtection: false,
        debugProtectionInterval: 0,
        disableConsoleOutput: false,
        identifierNamesGenerator: 'hexadecimal',
        log: false,
        numbersToExpressions: false,
        renameGlobals: false,
        selfDefending: true,
        simplify: true,
        splitStrings: false,
        stringArray: false,
        stringArrayCallsTransform: false,
        stringArrayCallsTransformThreshold: 0.5,
        stringArrayEncoding: [],
        stringArrayIndexShift: true,
        stringArrayRotate: true,
        stringArrayShuffle: true,
        stringArrayWrappersCount: 1,
        stringArrayWrappersChainedCalls: true,
        stringArrayWrappersParametersMaxCount: 2,
        stringArrayWrappersType: 'variable',
        stringArrayThreshold: 0.75,
        unicodeEscapeSequence: false,
    }
};
export default defineConfig(({mode}: { mode: string }): object => {
        const env: Record<string, string> = loadEnv(mode, process.cwd());
        return {
            publicDir: 'public',
            base: '/',
            resolve: {
                //设置别名
                alias: {
                    '@': path.resolve(__dirname, 'src')
                }
            },
            plugins: [
                vue(),
                vitePluginBundleObfuscator(defaultObfuscatorConfig),
                chunkSplitPlugin({
                    strategy: "default",
                    useEntryName: true,
                }),
                Components({
                    dts: true,
                    dirs: ['src/components', 'src/views'],
                    resolvers: [
                        AntDesignVueResolver({
                            importStyle: false,
                            resolveIcons: true
                        }),
                    ],
                }),
                AutoImport({

                    imports: ['vue', 'vue-router', 'pinia', '@vueuse/core'],
                    dts: 'auto-import.d.ts',
                    //ant-design-vue
                    resolvers: [AntDesignVueResolver({
                        importStyle: false,
                        resolveIcons: true
                    })],
                    eslintrc: {
                        enabled: false // 1、改为true用于生成eslint配置。2、生成后改回false,避免重复生成消耗
                    }
                }),
                nodePolyfills(),
                viteCompression({
                    filter: /\.(js|mjs|css|html)$/i, 
                    verbose: true,
                    disable: false,
                    threshold: 10240, 
                    algorithm: "gzip", 
                    ext: ".gz",
                    deleteOriginFile: true, 
                }),
                createHtmlPlugin({
                    minify: true,
                    /**
                     * 在这里写entry后,你将不需要在`index.html`内添加 script 标签,原有标签需要删除
                     * @default src/main.ts
                     */
                    entry: "src/main.ts",
                    /**
                     * 如果你想将 `index.html`存放在指定文件夹,可以修改它,否则不需要配置
                     * @default index.html
                     */
                    template: "index.html",
                    /**
                     * 需要注入 index.html ejs 模版的数据
                     */
                    inject: {
                        data: {
                            title: env.VITE_TITLE_NAME,
                        },
                    },
                }),
            ],
            css: {
                preprocessorOptions: {
                    scss: {
                        api: "modern-compiler",
                        javascriptEnabled: true,
                    },
                    less: {
                        javascriptEnabled: true,
                    },
                },
                modules: {

                    generateScopedName: "[name]__[local]___[hash:base64:5]",
                },

            },

            esbuild: {
                drop: env.VITE_NODE_ENV === 'production' ? ['console', 'debugger'] : [],
            },
            build: {
                outDir: "dist", // 指定输出路径
                assetsDir: "assets", // 指定生成静态文件目录
                assetsInlineLimit: "4096", // 小于此阈值的导入或引用资源将内联为 base64 编码
                cssCodeSplit: true, // 启用 CSS 代码拆分
                sourcemap: false, // 构建后是否生成 source map 文件
                minify: "esbuild", // 指定使用哪种混淆器
                write: true, // 启用将构建后的文件写入磁盘
                emptyOutDir: true, // 构建时清空该目录
                brotliSize: true, // 启用 brotli 压缩大小报告
                chunkSizeWarningLimit: 6000, // chunk 大小警告的限制
                watch: null, // 设置为 {} 则会启用 rollup 的监听器
                rollupOptions: {  // 自定义底层的 Rollup 打包配置
                    output: {
                        chunkFileNames: 'js/[name]-[hash].js', // 引入文件名的名称
                        entryFileNames: 'js/[name]-[hash].js', // 包的入口文件名称
                        assetFileNames: '[ext]/[name]-[hash].[ext]',// 资源文件像 字体,图片等
                    },
                }
            },
            server: {
                proxy: {
                    [env.VITE_APP_BASE_API]: {

                        target: env.VITE_API_BASE_URL,

                        changeOrigin: true,
                        rewrite: (path: string) => path.replace(RegExp(`^${env.VITE_APP_BASE_API}`), ""),
                    },
                },
            },
        };
    }
)
;

感谢反馈。package.json中的 type: "module" 这个配置先给去掉。稍晚一会,我会修复发新版本。

3517283258 commented 1 day ago

@z0ffy 好的,感谢!

z0ffy commented 1 day ago

@z0ffy 好的,感谢!

新版已发布,可以试一下。

3517283258 commented 1 day ago

@z0ffy yarn 库好像没更新,我用的yarn

z0ffy commented 1 day ago

@z0ffy yarn 库好像没更新,我用的yarn

https://yarn.nodejs.cn/package?q=vite-plugin-bundle&name=vite-plugin-bundle-obfuscator&version=1.2.1 我看已经有了,你指定版本试下

3517283258 commented 1 day ago

@z0ffy yarn 库好像没更新,我用的yarn

https://yarn.nodejs.cn/package?q=vite-plugin-bundle&name=vite-plugin-bundle-obfuscator&version=1.2.1 我看已经有了,你指定版本试下

image 奇怪,还是没有啊,镜像源也改成官方镜像了,也没有

z0ffy commented 1 day ago

@z0ffy yarn 库好像没更新,我用的yarn

https://yarn.nodejs.cn/package?q=vite-plugin-bundle&name=vite-plugin-bundle-obfuscator&version=1.2.1 我看已经有了,你指定版本试下

image 奇怪,还是没有啊,镜像源也改成官方镜像了,也没有

清缓存试试,yarn cache clean

3517283258 commented 1 day ago

@z0ffy yarn 库好像没更新,我用的yarn

https://yarn.nodejs.cn/package?q=vite-plugin-bundle&name=vite-plugin-bundle-obfuscator&version=1.2.1 我看已经有了,你指定版本试下

image 奇怪,还是没有啊,镜像源也改成官方镜像了,也没有

清缓存试试,yarn cache clean

OK,可以了,打包也没有问题,非常感谢!

z0ffy commented 1 day ago

@z0ffy yarn 库好像没更新,我用的yarn

https://yarn.nodejs.cn/package?q=vite-plugin-bundle&name=vite-plugin-bundle-obfuscator&version=1.2.1 我看已经有了,你指定版本试下

image 奇怪,还是没有啊,镜像源也改成官方镜像了,也没有

清缓存试试,yarn cache clean

OK,可以了,打包也没有问题,非常感谢!

好的👌