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.

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.
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.
npm install xml-loader
yarn add xml-loader
pnpm add xml-loader

Shows how to configure xml-loader in webpack and use it to import an XML file as JSON.

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