Skip to content

Instantly share code, notes, and snippets.

@mizchi
Created March 10, 2021 15:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mizchi/1a4e863979aab4593984f4a7d8c5160d to your computer and use it in GitHub Desktop.
Save mizchi/1a4e863979aab4593984f4a7d8c5160d to your computer and use it in GitHub Desktop.
// vite-plugin-raw
/*
How to use.
// vite.config.js
const raw = require('<this>')
module.exports = {
plugins: [raw()]
}
// import via raw
import foo from "./foo.js?raw";
console.log(foo);
*/
module.exports = () => ({
enforce: "post",
name: "raw",
resolveId(id) {
if (id.endsWith("?raw")) {
return id;
}
},
load(id) {
if (id.endsWith("?raw")) {
const fpath = id.replace("?raw", "");
const raw = fs.readFileSync(fpath, "utf-8");
return `export default ${JSON.stringify(raw)};`;
}
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment