Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Read file contents at build time via babel-plugin-macros or SWC plugin.

License

NotificationsYou must be signed in to change notification settings

pveyes/raw.macro

Repository files navigation

Actions StatusBabel Macro

Webpackraw-loader implemented asbabel-plugin-macros andSWC plugins

Installation

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.

Usage

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.

Custom Encoding

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");

Dynamic path import

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:

  1. You can only use up to two variables inside template literal. 1 for directory name, and 1 for file name.
  2. 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

SWC

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.

License

MIT


[8]ページ先頭

©2009-2025 Movatter.jp