Webpack XML Loader
raw JSON → 1.2.1 verified Sat Apr 25 auth: no javascript maintenance
A webpack loader that converts XML files into JSON objects using node-xml2js. Current stable version is 1.2.1. It supports query-string options to configure the xml2js parser, such as explicitChildren, and can be used both inline and via webpack config. Maintained as a simple, focused loader for webpack 1-4; does not support webpack 5 by default. Alternatives include raw-loader or custom loaders for more modern webpack setups.
Common errors
error Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type. ↓
cause Webpack cannot parse .xml files without a loader configured.
fix
Add xml-loader to your webpack config module.rules.
error Error: Cannot find module 'xml-loader' ↓
cause xml-loader is not installed or not in node_modules.
fix
Run npm install --save-dev xml-loader.
error require('xml!./data.xml') returns undefined ↓
cause You are using the deprecated ! prefix incorrectly or missing the loader name.
fix
Use require('xml-loader!./data.xml') with the full loader name.
Warnings
breaking Webpack 5 compatibility: xml-loader may not work out of the box with webpack 5. ↓
fix Use a more modern loader or configure with additional module rules.
deprecated Query string syntax for loader options is deprecated in webpack 4+. Use `options` object in config instead. ↓
fix Use { test: /\.xml$/, use: { loader: 'xml-loader', options: { explicitChildren: true } } }
gotcha The loader's return value is a JavaScript object, not a string. If you need the raw XML string, use raw-loader. ↓
fix Use raw-loader if you need the raw XML text.
gotcha All XML attributes are coerced to lowercase by default. This may cause breaking changes if you rely on case. ↓
fix Configure xml2js options via loader query or options to preserve case.
Install
npm install xml-loader yarn add xml-loader pnpm add xml-loader Imports
- default wrong
import { data } from 'xml-loader!./data.xml'correctimport data from 'xml-loader!./data.xml' - require wrong
const data = require('!xml-loader!./data.xml');correctconst data = require('xml-loader!./data.xml'); - webpack config wrong
module.exports = { module: { loaders: [ { test: /\.xml$/, loader: 'xml-loader' } ] } };correctmodule.exports = { module: { rules: [ { test: /\.xml$/, use: 'xml-loader' } ] } }; - query params wrong
require('xml-loader!./data.xml?explicitChildren=true')correctrequire('xml-loader?explicitChildren=true!./data.xml')
Quickstart
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.xml$/,
use: 'xml-loader'
}
]
}
};
// app.js
const data = require('./data.xml');
console.log(data); // parsed JSON object
// With options
const dataWithChildren = require('xml-loader?explicitChildren=true!./data.xml');
console.log(dataWithChildren);