Require a set of modules based on a DefinePlugin constant

后端 未结 2 1249
走了就别回头了
走了就别回头了 2021-01-15 11:00

I\'m trying to build a web application using Webpack, and I\'ve hit a bit of a wall with a particular part of the design - hopefully someone on here will have experience doi

2条回答
  •  -上瘾入骨i
    2021-01-15 11:28

    I came up with a decent(?) solution to this problem after taking bebraw's advice - thought I'd post it as an additional answer in case anyone runs into the same issue or wants to implement something similar. I'm using TypeScript, but the same approach would probably work fine in JavaScript, with or without ES6.

    Basically, I now have a directory called config in my src which contains a subdirectory for each customer, like so:

    config
    ├── dev
    ├── cust1
    └── cust2
    

    Each one of these contains an info.ts file, which exports constants such as REST endpoint URLs:

    export default {
        name: "Company Name",
        server: "http://localhost:8810",
        service: "ServiceName"
    }
    

    And a modules.ts file, which exports the array of modules to pass into my app's bootstrapper function:

    import util from "../../modules/util";
    import session from "../../modules/session";
    import shell from "../../modules/shell";
    import stock from "../../modules/stock";
    
    export default [
        util,
        session,
        shell,
        stock,
    ];
    

    These have to be separate - my initial implementation had one .ts file for each config, but this meant I ended up with a circular dependency whenever I tried to import the constants from within the modules.

    Then I just added a resolve.alias based on a command line argument:

    alias: {
        "config": path.join(__dirname, `src/config/${yargs.argv.env || "dev"}/`)
    }
    

    Now I can switch out what config/info and config/modules refer to just by calling:

    webpack --env dev
    webpack --env cust1
    webpack --env cust2
    

    I still need to see how this works out in practice, and maybe refine the interface for the different exports, but as a starting point I'm liking it so far!

提交回复
热议问题