raw-loader
raw JSON → 4.0.2 verified Sat Apr 25 auth: no javascript
Webpack loader that imports files as a string. Current stable version 4.0.2 (2020-10-09), maintained by webpack-contrib. Supports webpack 4 and 5. Key differentiator: minimal, zero-config loader for raw text files. Alternatives like file-loader or url-loader create separate files; raw-loader inlines content as a string. Enables ES module or CommonJS output via the `esModule` option (default true, changed in v4.0.0). Requires Node >= 10.13.0.
Common errors
error Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type. ↓
cause Raw-loader not configured for file extension in webpack config.
fix
Add rule:
{ test: /\.txt$/, use: 'raw-loader' } in webpack.config.js error Cannot find module 'raw-loader' ↓
cause raw-loader not installed or wrong devDependency.
fix
Run
npm install raw-loader --save-dev error Invalid options object. Options not matching the schema defined in schema-utils ↓
cause Unknown or malformed option passed to raw-loader.
fix
Check options: only
esModule (boolean) is supported. Remove any other options like modules (renamed) or typos. Warnings
breaking Minimum Node.js version changed ↓
fix Ensure Node.js >= 10.13.0
breaking ES module export became default in v2.0.0 ↓
fix For CommonJS output, set `esModule: false` in options.
deprecated The `modules` option (renamed to `esModule`) ↓
fix Use `esModule` instead of `modules`.
gotcha Inline loader syntax may conflict with other rules ↓
fix Prefix with `!!` to disable all other loaders: `import txt from '!!raw-loader!./file.txt';`
Install
npm install raw-loader yarn add raw-loader pnpm add raw-loader Imports
- default import (string content) wrong
const txt = require('./file.txt');correctimport txt from './file.txt'; - inline usage with webpack wrong
import txt from 'raw-loader!./file.txt'; // but missing !! to disable other loaderscorrectimport txt from 'raw-loader!./file.txt'; - webpack rule configuration wrong
module.exports = { module: { rules: [ { test: /\.txt$/i, loader: 'raw-loader' } ] } };correctmodule.exports = { module: { rules: [ { test: /\.txt$/i, use: 'raw-loader' } ] } };
Quickstart
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.txt$/i,
use: 'raw-loader',
},
],
},
};
// file.txt: Hello World
// entry.js
import content from './file.txt';
console.log(content); // 'Hello World'