Skip to content

wobsoriano/unplugin-strip-exports

Repository files navigation

unplugin-strip-exports

Remove specific named exports in your JavaScript code. Like getServerSideProps and getStaticProps of Next.js.

Install

pnpm add unplugin-strip-exports -D
Vite
// vite.config.ts
import StripExports from 'unplugin-strip-exports/vite'

export default defineConfig({
  plugins: [
    StripExports({
      match() {
        return ['getServerSideProps']
      }
    }),
  ],
})


Rollup
// rollup.config.js
import StripExports from 'unplugin-strip-exports/rollup'

export default {
  plugins: [
    StripExports({
      match() {
        return ['getServerSideProps']
      }
    }),
  ],
}


Webpack
// webpack.config.js
module.exports = {
  /* ... */
  plugins: [
    require('unplugin-strip-exports/webpack')({
      match() {
        return ['getServerSideProps']
      }
    })
  ]
}


esbuild
// esbuild.config.js
import { build } from 'esbuild'
import StripExports from 'unplugin-strip-exports/esbuild'

build({
  plugins: [StripExports({
    match() {
      return ['getServerSideProps']
    }
  })],
})


SvelteKit
// svelte.config.js
import { removeExports } from 'unplugin-strip-exports'

const config = {
  preprocess: [
    {
      script({ content }) {
        return removeExports(content, ['getServerSideProps'])
      }
    }
  ]
}


Now if you have a index.tsx:

import fs from 'fs'

export const getServerSideProps = () => {
  return {
    content: fs.readFileSync('./foo.txt', 'utf-8'),
  }
}

export default ({ content }) => {
  return <div>{content}</div>
}

The output will be:

export default ({ content }) => {
  return <div>{content}</div>
}

Advanced Usage

// vite.config.ts
import StripExports from 'unplugin-strip-exports/vite'

export default defineConfig({
  plugins: [
    StripExports({
      match(filepath, ssr) {
        // Ignore SSR build
        if (ssr)
          return

        // Remove getServerSideProps in "pages" in browser build
        if (filepath.startsWith(pagesDir))
          return ['getServerSideProps']
      }
    }),
  ],
})

Credits

This plugin is essentially a copy of babelTransformClientSidePages() util function of Rakkas.

License

MIT