alfian23

vite-babel-plugin

Jul 30th, 2021 (edited)
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const babel = require('@babel/core')
  2.  
  3. export default function babelPlugin() {
  4.   const runtimePublicPath = '/@virtual-babel'
  5.  
  6.   return {
  7.     name: 'vite-babel-plugin',
  8.     resolveId(id) {
  9.       if (id === runtimePublicPath) {
  10.         return runtimePublicPath
  11.       }
  12.     },
  13.     async transform(code, id, ssr) {
  14.       if (ssr) return
  15.       if (!id.endsWith('x') && !code.includes('react')) return
  16.       if (code.includes('<!DOCTYPE html>')) return
  17.  
  18.       const plugins = []
  19.       if (id.endsWith('.tsx')) {
  20.         plugins.push(require('@emotion/babel-plugin'))
  21.       }
  22.  
  23.       const parserPlugins = [
  24.         'jsx',
  25.         'importMeta',
  26.         'topLevelAwait',
  27.         'classProperties',
  28.         'classPrivateProperties',
  29.         'classPrivateMethods'
  30.       ]
  31.       if (/\.tsx?$/.test(id)) {
  32.         parserPlugins.push('typescript', 'decorators-legacy')
  33.       }
  34.  
  35.       const result = await babel.transformAsync(code, {
  36.         plugins,
  37.         babelrc: false,
  38.         ast: true,
  39.         sourceFileName: id,
  40.         configFile: false,
  41.         sourceMaps: true,
  42.         parserOpts: {
  43.           sourceType: 'module',
  44.           allowAwaitOutsideFunction: true,
  45.           plugins: parserPlugins
  46.         },
  47.       })
  48.       return { code: result.code, map: result.map }
  49.     }
  50.   }
  51. }
Add Comment
Please, Sign In to add comment