- Notifications
You must be signed in to change notification settings - Fork12
Read file contents at build time via babel-plugin-macros or SWC plugin.
License
pveyes/raw.macro
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Webpack
raw-loader
implemented asbabel-plugin-macros
andSWC plugins
In order to use raw.macro in your own project, you can use one of the following commands:
$ yarn add --dev raw.macro# or$ npm install --save-dev raw.macro
Make surebabel-plugin-macros
already installed. If you're usingCreate React App, it's installed by default.
Alternatively you can useSWC plugins and skip installingbabel-plugins-macros
entirely.
raw.macro is similar to Node’srequire
call:
importrawfrom"raw.macro";constmarkdown=raw("./README.md");
Note: Because raw.macro uses babel internally to replaceraw()
calls, your transpiled code won't be changed if you only change the file that you import. This is because from babel perspective, your JS file is unchanged
One workaround that you can do that doesn't involve restarting your build system is making small changes where you putraw()
calls, for example by addingconsole.log()
with different content.
If you want to use custom encoding (by default it will useutf-8
), you can pass it to the second argument
importrawfrom"raw.macro";constbinary=raw("./path/to/binary","binary");
You can also use import dynamic path usingtemplate literal. You can even use them inside a function / React component!
importrawfrom"raw.macro";functionArticle(props){constcontent=raw(`../content/${props.locale}.md`);return<Markdowncontent={content}/>;}
This method has 2 caveats:
- You can only use up to two variables inside template literal. 1 for directory name, and 1 for file name.
- Using dynamic path import will includes all files that matches your dynamic path, which can make your JS bundle a lot bigger. This is also partly the reason of limitation described in #1
You can also useraw.macro
in a swc-based project (e.g: Next.js) by using the SWC plugins.
Due to how the plugins is loaded, you have to passrootDir
option pointing to the root directory of your project (where yournode_modules
directory lives). Typically it's enough to pass__dirname
.
// next.config.jsmodule.exports={experimental:{swcPlugins:[["raw.macro/swc",{rootDir:__dirname,},],],},};
Note that currently SWC plugins only support reading text file from relative path and node_modules content. Using custom encoding or dynamic path import is not supported.
MIT
About
Read file contents at build time via babel-plugin-macros or SWC plugin.