wpw-final/frontend/vite.config.ts
2022-12-02 20:40:23 +07:00

349 lines
11 KiB
TypeScript

import { fileURLToPath, URL } from 'node:url';
import { defineConfig, optimizeDeps } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import { esbuildCommonjs, viteCommonjs } from '@originjs/vite-plugin-commonjs';
import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill';
import { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill';
import { Plugin } from 'rollup';
import { splitVendorChunkPlugin } from 'vite';
import rollupNodePolyfills from 'rollup-plugin-node-polyfills';
import viteNodePolyfills from 'vite-plugin-node-stdlib-browser';
import { nodeResolve as rollupNodeResolve } from '@rollup/plugin-node-resolve';
import rollupCommonjs from '@rollup/plugin-commonjs';
import terser from '@rollup/plugin-terser';
import compiler from '@ampproject/rollup-plugin-closure-compiler';
import { babel, getBabelOutputPlugin } from '@rollup/plugin-babel';
import legacy from '@vitejs/plugin-legacy';
import uglify from '@lopatnov/rollup-plugin-uglify';
import { obfuscator } from 'rollup-obfuscator';
import { chunkSplitPlugin } from 'vite-plugin-chunk-split';
import { dependencies } from './package.json';
import polyfillAliases from './vite-polyfill-aliases';
import { resolve } from 'node:path';
export function injectSecPlugin(mode) {
return ['production', 'live'].indexOf(mode) !== -1 ? secPlugins : [];
}
export const secPlugins: Plugin[] = [
// NOT WORK.
// babel({
// babelHelpers: 'bundled',
// presets: [[
// "@babel/preset-env",
// {
// "corejs": "3.22",
// "useBuiltIns": "entry",//"usage",
// "targets": {
// "ie": "11"
// }
// }
// ]],
// }),
// terser({
// parse: {},
// // compress: {
// // dead_code: true,
// // keep_fnames: false,
// // },
// // mangle: {
// // keep_fnames: false,
// // properties: {
// // builtins: false,
// // // keep_quoted: false,
// // // nth_identifier: ,
// // // reserved: [
// // // '_mergeNamespaces',
// // // 'polyfill',
// // // 'class', 'alt', 'src', 'href', 'target', "value", "type", "onClick"
// // // ],
// // // regex: /^(T*Protocol|T*Transport|T*Error|transport|*Exception|write*|read*|skip|*Zigzag|zigzag*|VERSION*|TYPE*|COMPACT*|HEADER*|FLAG*|TINFO*|MAX*|Varint*|varint*|CT_*|*TType|flush)$/,
// // // regex: /(thrift|Thrift|Protocol|Transport|Error|transport|Exception|write|read|skip|zigzag|VERSION|TYPE|COMPACT|HEADER|FLAG|TINFO|MAX|Varint|varint|CT|TType|flush)/,
// // },
// // },
// mangle: {
// keep_classnames: true,
// keep_fnames: true,
// properties: {
// keep_quoted: true,
// // builtins: false,
// // ||SET|LIST|||I64|
// // regex: /(^_|^is|eject|esolve|set|next|query|create|STRING|UTF7|UTF8|UTF16|DOUBLE|Error|error|dir|MAP|STOP|VOID|thrift|PROTOCOL|METHOD|method|UNKNOWN|TRANSFORM|VALID|SEQUENCE|RESULT|ERROR|CALL|REPLY|stack|field|Field|ONEWAY|EXCEPTION|client|Client|Type|socket|watch|mount|install|comp|emit|prop|destroy|Recv|Send|service|Service|Thrift|Protocol|Transport|transport|protocol|output|Error|transport|Exception|write|read|skip|zigzag|VERSION|TYPE|COMPACT|HEADER|FLAG|TINFO|MAX|Varint|varint|CT|TType|trans|call|url|xhr|XHR|header|log|before|after|update|insert|console|read|write|flush)/,
// regex: new RegExp(
// [
// // var prefixed with underscore
// '^_',
// // thrift words
// ...(
// '' +
// // 'Thrift|thrift|Field|^field|Protocol|Transport|Connection|Client|Protocol|Service|Type|Error|Exception|' +
// // // 'Recv|recv|Send|send|'+
// // 'write|read|Socket|socket|trans|prot|rotoco|tack|ervice|Trans|' +
// // 'CALL|REPLY|ONEWAY|VALID|^UNK|BAD_|IMPL|_LIMIT|SIZE_|EXCEPTION|RESULT|ERROR|TRANSFORM|PROTOCOL|VERSION|TYPE|CT|TType|METHOD|' +
// // '^STOP|^VOID|^STRING|^LIST|^MAP|^SET|^UTF7|^UTF8|^UTF16|^DOUBLE|^I64|^I32|^I16|^BOOL|^BYTE|^I08|' +
// // 'headers|igzag|^xhr|^XHR|^flush' +
// ''
// )
// .split('|')
// .map((x) => x.trim())
// .filter((x) => x != ''),
// ].join('|'),
// '',
// ),
// },
// // eval: true,
// // module: true,
// // toplevel: true,
// // safari10: true,
// // properties: false,
// },
// format: {
// comments: 'some',
// },
// }),
// compiler({
// // https://github.com/google/closure-compiler/wiki/Flags-and-Options
// // https://github.com/google/closure-compiler/blob/5707cfe4fa3be9cfe9b2f713a47f0080b08c57cb/src/com/google/javascript/jscomp/parsing/ParserRunner.java#L176
// // compilation_level: 'ADVANCED',
// // warning_level: 'VERBOSE',
// // language_in: 'ECMASCRIPT_NEXT',
// // language_in: 'STABLE',
// // current workaround, modify renderChunk preCompileOutput.
// // ConstTransform pre
// // LiteralComputedKeys post
// language_in: 'unstable',
// // language_out: 'ECMASCRIPT_NEXT',
// jscomp_off: ['undefinedVars'],
// }),
obfuscator({
compact: true,
forceTransformStrings: Array.from(
new Set([
'thrift',
'Thrift',
'vite',
'Vite',
'vue',
'Vue',
...Object.keys(dependencies)
.map((x) => x.replace('@', '-').replace('/', '-'))
.map((x) => x.split('-'))
.flat()
.filter((x) => x != ''),
]),
),
splitStrings: true,
stringArray: true,
// stringArrayEncoding: ['base64', 'none'], // 'rc4',
stringArrayThreshold: 0.8,
// stringArrayIndexShift: true,
// stringArrayWrappersChainedCalls: true,
// stringArrayRotate: true,
// stringArrayCallsTransform: true,
selfDefending: false,
// controlFlowFlattening: true,
// controlFlowFlatteningThreshold: 0.8,
// transformObjectKeys: true,
renameGlobals: false,
// BROKEN!
// renameProperties: true,
// renamePropertiesMode: 'safe',
}),
terser({
compress: {
reduce_funcs: true,
reduce_vars: true,
},
mangle: {
properties: {
// builtins: false,
keep_quoted: true,
regex: /^_/, // obfuscator underscore variable
},
eval: true,
module: true,
toplevel: true,
safari10: true,
},
format: {
comments: 'some',
},
}),
];
// https://vitejs.dev/config/
export default defineConfig(({ command, mode, ssrBuild }) => {
return {
plugins: [viteCommonjs(), vue(), vueJsx()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
'@thriftgen': fileURLToPath(new URL('./gen', import.meta.url)),
...polyfillAliases,
},
},
define: {
global: 'window',
},
optimizeDeps: {
esbuildOptions: {
define: { global: 'globalThis' },
plugins: [
NodeGlobalsPolyfillPlugin({
process: true,
buffer: true,
}),
NodeModulesPolyfillPlugin(),
],
},
// exclude: ['flowbite', 'flowbite-vue', 'thrift'],
},
build: {
outDir: '../public',
manifest: true,
minify: false,
rollupOptions: {
input: {
main: resolve(__dirname, 'index.html'),
},
output: {
// to be able to use manual chunk - iife
// inlineDynamicImports: true,
manualChunks(id, { getModuleInfo, getModuleIds }) {
// const dynImpIds = getModuleInfo(id).dynamicImporters;
// if (/(gen\/|thrift|Thrift|util|events|inherits|WebSocket|Int64|ws)/.test(id)) return 'ext';
// if (/flowbite/.test(id)) return 'flowbite';
// if (/data-table/.test(id)) return 'edt';
// if (/scrollbar/.test(id)) return 'scrollbar';
// if (/(node_modules)/.test(id)) return 'vendor';
// if (id in dependencies) {
// return 'vendor';
// }
},
},
plugins: [
rollupNodePolyfills(),
rollupNodeResolve(),
rollupCommonjs({}),
esbuildCommonjs(['thrift']),
],
},
},
};
});
export const x = defineConfig(({ command, mode, ssrBuild }) => {
return {
plugins: [viteNodePolyfills(), viteCommonjs(), vue(), vueJsx()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
'@thriftgen': fileURLToPath(new URL('./gen', import.meta.url)),
// '@flowbite-vue': fileURLToPath(new URL('./3rdparty/flowbite-vue/src', import.meta.url)),
...polyfillAliases,
},
},
optimizeDeps: {
esbuildOptions: {
define: { global: 'globalThis' },
plugins: [
NodeGlobalsPolyfillPlugin({
process: true,
buffer: true,
}),
NodeModulesPolyfillPlugin(),
],
},
// include: [],
// exclude: [/@thriftgen/],
// exclude: [
// 'flowbite',
// 'flowbite-vue',
// 'thrift',
// 'vue3-easy-data-table',
// 'vue3-perfect-scrollbar',
// ...['structs_types', 'exceptions_types', 'CoreService'].map((x) => '@thriftgen/' + x),
// ],
},
build: {
outDir: '../public',
manifest: true,
// minify: 'terser',
minify: false,
// target: 'esnext',
rollupOptions: {
// input: {
// main: resolve(__dirname, 'index.html'),
// },
// output: {
// // format: 'iife',
// // format: 'cjs',
// globals: {
// // vue: "Vue"
// },
// // to be able to use manual chunk - iife
// // inlineDynamicImports: true,
// // manualChunks(id, { getModuleInfo, getModuleIds }) {
// // // if (/(gen\/|thrift|Thrift|util|inherits|WebSocket|Int64)/.test(id)) return 'ext';
// // // const dynImpIds = getModuleInfo(id).dynamicImporters;
// // if (/data-table/.test(id)) return 'edt';
// // if (/(node_modules)/.test(id)) return 'vendor';
// // // if (id in dependencies) {
// // // return 'vendor';
// // // }
// // },
// },
external: [
// "vue",
],
plugins: [
// chunkSplitPlugin({
// strategy: 'single-vendor',
// customSplitting: {
// 'thrift-vendor': ['thrift'],
// 'flowbite-vendor': ['flowbite'],
// },
// }),
// splitVendorChunkPlugin(),
rollupNodePolyfills(),
rollupNodeResolve(),
rollupCommonjs({}),
esbuildCommonjs(['thrift']),
// NOT WORK.
// ...legacy({
// targets: ['defaults', 'IE 11'],
// }),
...injectSecPlugin(mode),
],
},
},
};
});