jeffbRTC
jeffbRTC

Reputation: 2069

How to import js file as string with Rollup?

In Webpack, we have raw-loader to import files like .js as strings. I'm using Rollup. Does Rollup has anything similar to that?

Upvotes: 2

Views: 3652

Answers (3)

Deadalus _
Deadalus _

Reputation: 76

For vite-like behaviour, you can use this simple plugin function:

import { readFileSync } from 'fs'

const raw = () => {
  return {
    name: 'raw',
    load(id) {
      if (id.endsWith('?raw')) {
        const content = readFileSync(id.replace('?raw', '')).toString('utf-8')
        return `export default \`${content.replace(/`/g, '\\`')}\``
      }
    }
  }
}

Upvotes: 1

ExposedCat
ExposedCat

Reputation: 121

Update for August 2024:

rollup-plugin-string is dead, there is a new rollup-plugin-string-import with TS support and other additional features

Upvotes: 1

jeffbRTC
jeffbRTC

Reputation: 2069

Turns out, you need a plugin for that.

I found one today https://github.com/TrySound/rollup-plugin-string

Upvotes: 3

Related Questions