@greenwood/plugin-import-raw
v0.34.0
Published
A Greenwood plugin to allow you to use ESM (import) syntax to load any file content as a string.
Maintainers
Readme
@greenwood/plugin-import-raw
Overview
A Greenwood plugin to use ESM (import) syntax to load any file contents as a string exported as a JavaScript module. Inspired by webpack's raw loader. For more information and complete docs on Greenwood, please visit our website.
This package assumes you already have
@greenwood/cliinstalled.
Installation
You can use your favorite JavaScript package manager to install this package.
# npm
$ npm i -D @greenwood/plugin-import-raw
# yarn
$ yarn add @greenwood/plugin-import-raw --dev
# npm
$ pnpm add -D @greenwood/plugin-import-rawUsage
Add this plugin to your greenwood.config.js:
import { greenwoodPluginImportRaw } from '@greenwood/plugin-import-raw';
export default {
// ...
plugins: [
greenwoodPluginImportRaw()
]
}This will then allow you to use ESM (import) to include any file as an arbitrary string exported as a JavaScript module.
import css from '../path/to/styles.css?type=raw'; // must be a relative path per ESM spec
console.log(css); // h1 { color: red }For libraries like Material Web Components, this plugin will resolve references to some-file.css if the equivalent exists that ends in .js (e.g. styles.css.js).
Types
Types should automatically be inferred through this package's exports map, but can be referenced explicitly in both JavaScript (JSDoc) and TypeScript files if needed.
/** @type {import('@greenwood/plugin-import-raw').ImportRawPlugin} */import type { ImportRawPlugin } from '@greenwood/plugin-import-raw';To support typing of ?type=raw imports, you can add this type definition to your project:
declare module "*?type=raw" {
const content: string;
export default content;
}Options
Matches
Optionally, you can provide an array of "matcher" patterns for the plugin to transform custom paths, which can be useful for handling imports you can't change, like third party files in node_modules.
import { greenwoodPluginImportRaw } from '@greenwood/plugin-import-raw';
export default {
plugins: [
greenwoodPluginImportRaw({
matches: [
'/node_modules/some-package/dist/styles.css'
]
})
]
}Import Map Extensions
As import maps treat all paths as unique even for query strings, this import:
import pauseSvg from 'heroicons/24/solid/pause.svg';is not the same as this one:
import pauseSvg from 'heroicons/24/solid/pause.svg?type=raw';To include entries in an import map for resources imported by this plugin, the importMapExtensions option can be used to add query string import map entries for all entries that end with the matching extension(s) provided.
import { greenwoodPluginImportRaw } from '@greenwood/plugin-import-raw';
export default {
plugins: [
greenwoodPluginImportRaw({
importMapExtensions: ['svg']
})
]
}