Skip to content

Commit

Permalink
refactor: vite config
Browse files Browse the repository at this point in the history
  • Loading branch information
TurtIeSocks committed Jan 24, 2024
1 parent 719aa6e commit 0685191
Show file tree
Hide file tree
Showing 10 changed files with 604 additions and 385 deletions.
2 changes: 0 additions & 2 deletions ReactMap.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable import/extensions */

const { build } = require('vite')

const { log, HELPERS } = require('@rm/logger')
Expand Down
10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -180,14 +180,15 @@
"@commitlint/cli": "^17.2.0",
"@commitlint/config-conventional": "^17.2.0",
"@rm/types": "*",
"@rm/vite-plugins": "*",
"@semantic-release/changelog": "^6.0.1",
"@semantic-release/git": "^10.0.1",
"@sentry/vite-plugin": "2.2.1",
"@sentry/vite-plugin": "2.10.3",
"@types/dlv": "^1.1.2",
"@types/node": "^18",
"@types/react": "^18.2.20",
"@types/react-dom": "^18.0.9",
"@vitejs/plugin-react": "4.0.0",
"@vitejs/plugin-react": "4.2.1",
"commitizen": "^4.2.5",
"cz-conventional-commit": "^1.0.6",
"eslint": "^8.44.0",
Expand All @@ -205,9 +206,8 @@
"prettier": "^2.8.8",
"rollup-plugin-delete": "^2.0.0",
"semantic-release": "^19.0.5",
"vite": "4.5.2",
"vite-plugin-checker": "0.6.0",
"vite-plugin-static-copy": "0.16.0"
"vite": "5.0.12",
"vite-plugin-checker": "0.6.0"
},
"engines": {
"node": ">=18",
Expand Down
47 changes: 47 additions & 0 deletions packages/vite-plugins/lib/customFile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// @ts-check
const { extname } = require('path')
const fs = require('fs')

/**
* @param {boolean} isDevelopment
* @returns {import('vite').Plugin}
*/
const customFilePlugin = (isDevelopment) => {
const fileRegex = /\.(jsx?|css)$/
const customPaths = []
return {
name: 'vite-plugin-custom-file-checker',
load(id) {
if (fileRegex.test(id) && !/node_modules/.test(id)) {
const ext = extname(id)
const newPath = id.replace(ext, `.custom${ext}`)
if (fs.existsSync(newPath)) {
customPaths.push(newPath)
return {
code: fs.readFileSync(newPath, 'utf8'),
map: null,
}
}
}
},
buildEnd() {
if (customPaths.length && !isDevelopment) {
this.warn(`
======================================================
WARNING:
Custom files aren't officially supported
Be sure to watch for breaking changes!
${customPaths.map((x, i) => ` ${i + 1}. src/${x.split('src/')[1]}`).join('\n')}
======================================================
`)
}
},
}
}

module.exports = {
customFilePlugin,
}
26 changes: 26 additions & 0 deletions packages/vite-plugins/lib/favicon.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// @ts-check
const { resolve } = require('path')
const fs = require('fs')

/**
* @returns {import('vite').Plugin}
*/
const faviconPlugin = () => ({
name: 'vite-plugin-locales',
generateBundle() {
const favicon = fs.existsSync(
resolve(__dirname, '../../../public/favicon/favicon.ico'),
)
? resolve(__dirname, '../../../public/favicon/favicon.ico')
: resolve(__dirname, '../../../public/favicon/fallback.ico')
this.emitFile({
type: 'asset',
fileName: 'favicon.ico',
source: fs.readFileSync(favicon),
})
},
})

module.exports = {
faviconPlugin,
}
11 changes: 11 additions & 0 deletions packages/vite-plugins/lib/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const { localePlugin } = require('./locale')
const { faviconPlugin } = require('./favicon')
const { muteWarningsPlugin } = require('./muteWarnings')
const { customFilePlugin } = require('./customFile')

module.exports = {
localePlugin,
faviconPlugin,
muteWarningsPlugin,
customFilePlugin,
}
34 changes: 34 additions & 0 deletions packages/vite-plugins/lib/locale.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// @ts-check
const { join } = require('path')

const { create, writeAll } = require('@rm/locales')

/**
* @param {boolean} isDevelopment
* @returns {import('vite').Plugin}
*/
const localePlugin = (isDevelopment) => ({
name: 'vite-plugin-locales',
async buildStart() {
if (!isDevelopment) return
const localeObj = await create()
await writeAll(localeObj, true, __dirname, './public/locales')
},
async generateBundle() {
if (isDevelopment) return
const localeObj = await create()

Object.entries(localeObj).forEach(([locale, translations]) => {
const fileName = join('locales', locale, 'translation.json')
this.emitFile({
type: 'asset',
fileName,
source: JSON.stringify(translations),
})
})
},
})

module.exports = {
localePlugin,
}
51 changes: 51 additions & 0 deletions packages/vite-plugins/lib/muteWarnings.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// @ts-check

/**
* @param {string[][]} warningsToIgnore
* @returns {import('vite').Plugin}
*/
const muteWarningsPlugin = (warningsToIgnore) => {
const mutedMessages = new Set()
return {
name: 'mute-warnings',
enforce: 'pre',
config: (userConfig) => ({
build: {
rollupOptions: {
onwarn(warning, defaultHandler) {
if (warning.code) {
const muted = warningsToIgnore.find(
([code, message]) =>
code == warning.code && warning.message.includes(message),
)

if (muted) {
mutedMessages.add(muted.join())
return
}
}

if (userConfig.build?.rollupOptions?.onwarn) {
userConfig.build.rollupOptions.onwarn(warning, defaultHandler)
} else {
defaultHandler(warning)
}
},
},
},
}),
closeBundle() {
const diff = warningsToIgnore.filter((x) => !mutedMessages.has(x.join()))
if (diff.length > 0) {
this.warn(
'Some of your muted warnings never appeared during the build process:',
)
diff.forEach((m) => this.warn(`- ${m.join(': ')}`))
}
},
}
}

module.exports = {
muteWarningsPlugin,
}
20 changes: 20 additions & 0 deletions packages/vite-plugins/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "@rm/vite-plugins",
"version": "0.1.0",
"private": true,
"main": "./lib/index.js",
"scripts": {
"sort": "npx sort-package-json",
"depCheck": "npx depcheck",
"lint": "eslint \"**/*.{js,jsx}\"",
"lint:fix": "eslint \"**/*.{js,jsx}\" --fix",
"prettier": "prettier --check \"**/*.{css,html,js,jsx,yml}\"",
"prettier:fix": "prettier --write \"**/*.{css,html,js,jsx,yml}\""
},
"dependencies": {
"@rm/locales": "*"
},
"devDependencies": {
"vite": "5.0.12"
}
}
93 changes: 13 additions & 80 deletions vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,82 +5,22 @@
const { defineConfig, loadEnv } = require('vite')
const { default: react } = require('@vitejs/plugin-react')
const { default: checker } = require('vite-plugin-checker')
const { viteStaticCopy } = require('vite-plugin-static-copy')
const removeFiles = require('rollup-plugin-delete')
const { join, resolve, extname } = require('path')
const { resolve } = require('path')
const fs = require('fs')
const { sentryVitePlugin } = require('@sentry/vite-plugin')

const config = require('@rm/config')
const { log, HELPERS } = require('@rm/logger')
const { create, writeAll, locales } = require('@rm/locales')
const { locales } = require('@rm/locales')
const {
faviconPlugin,
customFilePlugin,
localePlugin,
muteWarningsPlugin,
} = require('@rm/vite-plugins')

/**
* @param {boolean} isDevelopment
* @returns {import('vite').Plugin}
*/
const customFilePlugin = (isDevelopment) => {
const fileRegex = /\.(jsx?|css)$/
const customPaths = []
return {
name: 'vite-plugin-custom-file-checker',
load(id) {
if (fileRegex.test(id) && !/node_modules/.test(id)) {
const ext = extname(id)
const newPath = id.replace(ext, `.custom${ext}`)
if (fs.existsSync(newPath)) {
customPaths.push(newPath)
return {
code: fs.readFileSync(newPath, 'utf8'),
map: null,
}
}
}
},
buildEnd() {
if (customPaths.length && !isDevelopment) {
log.warn(`
======================================================
WARNING:
Custom files aren't officially supported
Be sure to watch for breaking changes!
${customPaths.map((x, i) => ` ${i + 1}. src/${x.split('src/')[1]}`).join('\n')}
======================================================
`)
}
},
}
}

/**
* @param {boolean} isDevelopment
* @returns {import('vite').Plugin}
*/
const localePlugin = (isDevelopment) => ({
name: 'vite-plugin-locales',
async buildStart() {
if (!isDevelopment) return
const localeObj = await create()
await writeAll(localeObj, true, __dirname, './public/locales')
},
async generateBundle() {
if (isDevelopment) return
const localeObj = await create()

Object.entries(localeObj).forEach(([locale, translations]) => {
const fileName = join('locales', locale, 'translation.json')
this.emitFile({
type: 'asset',
fileName,
source: JSON.stringify(translations),
})
})
},
})

const viteConfig = defineConfig(async ({ mode }) => {
const viteConfig = defineConfig(({ mode }) => {
const env = loadEnv(mode, resolve(process.cwd(), './'), '')
const isRelease = process.argv.includes('-r')
const isDevelopment = mode === 'development'
Expand Down Expand Up @@ -141,17 +81,6 @@ const viteConfig = defineConfig(async ({ mode }) => {
]
: []),
...(hasCustom ? [customFilePlugin(isDevelopment)] : []),
viteStaticCopy({
targets: [
{
src: fs.existsSync(resolve(__dirname, 'public/favicon/favicon.ico'))
? resolve(__dirname, 'public/favicon/favicon.ico')
: resolve(__dirname, 'public/favicon/fallback.ico'),
dest: '.',
rename: 'favicon.ico',
},
],
}),
...(sentry.authToken && sentry.org && sentry.project
? [
sentryVitePlugin({
Expand All @@ -162,6 +91,10 @@ const viteConfig = defineConfig(async ({ mode }) => {
]
: []),
localePlugin(isDevelopment),
faviconPlugin(),
muteWarningsPlugin([
['SOURCEMAP_ERROR', "Can't resolve original location of error"],
]),
],
optimizeDeps: isDevelopment ? { exclude: ['@mui/*'] } : undefined,
publicDir: 'public',
Expand Down
Loading

0 comments on commit 0685191

Please sign in to comment.