You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何排序config.xml并更新package.json?Cordova配置规整咨询

Great questions—dealing with config.xml chaos is a common pain point with Cordova, especially when plugins and platforms keep modifying it. Let's break down your questions one by one:

1. Sorting config.xml and Syncing with package.json

Absolutely, there are reliable ways to handle this:

  • Use a dedicated npm package for sorting: Tools like cordova-config-sort can automatically organize elements in your config.xml (preferences, plugins, platforms, etc.) into a consistent, alphabetical order. Install it via:

    npm install cordova-config-sort --save-dev
    

    Add a script to your package.json to make sorting easy:

    "scripts": {
      "sort-config": "cordova-config-sort"
    }
    

    Run npm run sort-config whenever you need to tidy up your config.xml.

  • Sync changes with package.json: Cordova automatically syncs plugin/platform info between config.xml and package.json during operations like cordova prepare or cordova plugin add. After sorting config.xml, you can explicitly sync updates to package.json with:

    cordova plugin save
    

    This updates the cordova.plugins and dependencies sections to match your sorted config.xml. Conversely, if you modify package.json first, running cordova prepare will sync those changes back to config.xml.

    Pro tip: Always back up config.xml before running sorting tools to avoid accidental data loss.

2. Using Cordova Hooks to Maintain Consistent Order

Yes! Hooks are designed exactly for this kind of automated cleanup. Here's how to set it up:

Which Cordova Lifecycle Stages to Target

You want the sorting to run right after any operation that modifies config.xml. The most reliable stages are:

  • after_prepare: A catch-all that runs after cordova prepare (which triggers after plugin/platform installs/removes)
  • after_plugin_install: Runs immediately after a plugin is added
  • after_platform_install: Runs immediately after a platform is added

Binding to after_prepare is a safe default, but adding hooks to the plugin/platform stages ensures sorting happens instantly after a change is made.

Step-by-Step Hook Implementation

  1. Create a hook script: In your project's .cordova/hooks directory, create a file like 010-sort-config.js (the numeric prefix ensures it runs early in the hook sequence).

  2. Write the sorting logic: Use Node.js and an XML parser like xml2js to read, sort, and rewrite config.xml. Here's a basic working example:

    #!/usr/bin/env node
    const fs = require('fs');
    const xml2js = require('xml2js');
    
    const configPath = './config.xml';
    
    fs.readFile(configPath, 'utf8', (err, data) => {
      if (err) throw err;
    
      xml2js.parseString(data, { preserveWhitespace: true }, (parseErr, result) => {
        if (parseErr) throw parseErr;
    
        const widget = result.widget[0];
        // Sort preferences by name attribute
        if (widget.preference) {
          widget.preference.sort((a, b) => {
            const nameA = a.$.name.toLowerCase();
            const nameB = b.$.name.toLowerCase();
            return nameA.localeCompare(nameB);
          });
        }
        // Sort plugins by their ID
        if (widget.plugin) {
          widget.plugin.sort((a, b) => {
            const idA = a.$.id.toLowerCase();
            const idB = b.$.id.toLowerCase();
            return idA.localeCompare(idB);
          });
        }
        // Sort platforms by name
        if (widget.platform) {
          widget.platform.sort((a, b) => {
            const nameA = a.$.name.toLowerCase();
            const nameB = b.$.name.toLowerCase();
            return nameA.localeCompare(nameB);
          });
        }
    
        const builder = new xml2js.Builder({
          preserveWhitespace: true,
          xmldec: { version: '1.0', encoding: 'utf-8' }
        });
        const sortedXml = builder.buildObject(result);
    
        fs.writeFile(configPath, sortedXml, 'utf8', (writeErr) => {
          if (writeErr) throw writeErr;
          console.log('✅ config.xml sorted successfully');
        });
      });
    });
    
  3. Install dependencies: Add xml2js as a dev dependency:

    npm install xml2js --save-dev
    
  4. Make the script executable: On Linux/macOS, run:

    chmod +x .cordova/hooks/010-sort-config.js
    

Now, every time you run cordova prepare, cordova plugin add, or cordova platform add, the hook will automatically sort your config.xml into a predictable, consistent order.


内容的提问来源于stack exchange,提问作者pom421

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:59:11