Skip to content

Commit

Permalink
Support raw data imports (#296)
Browse files Browse the repository at this point in the history
  • Loading branch information
huozhi authored Dec 6, 2023
1 parent 93da819 commit ace8483
Show file tree
Hide file tree
Showing 6 changed files with 43 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/build-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import replace from '@rollup/plugin-replace'
import esmShim from '@rollup/plugin-esm-shim'
import { sizeCollector } from './plugins/size-plugin'
import { inlineCss } from './plugins/inline-css'
import { rawContent } from './plugins/raw-plugin'
import preserveDirectives from 'rollup-preserve-directives'
import {
getTypings,
Expand Down Expand Up @@ -175,6 +176,7 @@ async function buildInputConfig(
: [
...commonPlugins,
inlineCss({ exclude: /node_modules/ }),
rawContent({ exclude: /node_modules/ }),
preserveDirectives(),
replace({
values: getBuildEnv(options.env || []),
Expand Down
22 changes: 22 additions & 0 deletions src/plugins/raw-plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { type FilterPattern, createFilter } from '@rollup/pluginutils'
import type { Plugin } from 'rollup'

export function rawContent({ exclude }: { exclude: FilterPattern }): Plugin {
/\.(data|txt)$/
const filter = createFilter(['**/*.data', '**/*.txt'], exclude)

return {
name: "string",

transform(code, id) {
if (filter(id)) {
return {
code: `export default ${JSON.stringify(code)}`,
map: undefined,
}
}
return undefined
}
}
}

11 changes: 11 additions & 0 deletions test/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,17 @@ const testCases: {
expect(cjsOutput).not.toContain('import.meta.url')
},
},
{
name: 'raw-data',
args: [],
async expected(dir) {
const distFile = join(dir, './dist/index.js')
expect(await existsFile(distFile)).toBe(true)
expect(await fs.readFile(distFile, 'utf-8')).toContain(
`"thisismydata"`,
)
},
}
]

async function runBundle(
Expand Down
4 changes: 4 additions & 0 deletions test/integration/raw-data/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"type": "module",
"exports": "./dist/index.js"
}
1 change: 1 addition & 0 deletions test/integration/raw-data/src/content.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
thisismydata
3 changes: 3 additions & 0 deletions test/integration/raw-data/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import content from './content.txt'

export const data = content

0 comments on commit ace8483

Please sign in to comment.