Optimize/build modules under parallel directories using the same config file in RequireJS

StackOverflow https://stackoverflow.com/questions/8982133

  •  12-11-2019
  •  | 
  •  

質問

I have a feeling that the title just might not be explanatory :)

Setup

Suppose that I have the following structure:

enter image description here

where app.js files are main bootstrapping/entry modules for the applications that look like this:

app01

require.config({});

require([
    'app/component1.js'
], 
function(component){
    // do something with component1
});

app02

require.config({});

require([
    'app/component2.js'
], 
function(component){
    // do something with component2
});

which both work with appropriate index.html files.

I have a RequireJS build configuration file (assume correct placement related to the paths) for app01:

({
    appDir: 'apps/app01',
    baseUrl: '.',
    dir: 'built_apps/app01',
    optimize: 'closure',
    paths: {
    },

    modules: [
        {
            name: 'app'
        }
    ]
})

which works just fine. Similar file (replacing app01 with app02) works just fine for app02.

Problem/target

Now I want to be able to run RequireJS build tool (using Google Closure with Rhino under Ant, not that it really matters in this case) for both app01 and app02 applications using the same build configuration file and, preferably, without actually listing all the apps by name (since the number and names may vary over time).

Basically I expect (or rather hope) to have something like this:

({
    appDir: 'apps',
    baseUrl: '.',
    dir: 'built_apps',
    optimize: 'closure',
    paths: {

    },

    modules: [
        {
            name: 'app*/app' // notice the wildcard
        }
    ]
})

which would run over built_apps directory, find all apps under app*/app and optimize each one of them.

I know I can use Ant to create such build configuration file on the fly per app, run build against it and then clean up, but I'd rather have RequireJS solution.

Is there a way to do something like this with RequireJS?

役に立ちましたか?

解決

There's no built-in wildcarding configuration for RequireJS. One way or another, you'll need code to do this. I'll observe that what you're asking for here amounts to translating a wildcard into some kind of implicit iteration on the module objects, akin to what mustache.js provides for its templates. IMO, that's a fairly brittle and limited approach in this context.

Instead, I recommend generating your modules array programmatically in JavaScript right in the build config. Recall, the build config is JavaScript not just a JSON data structure. This gives you sophisticated scripting capabilities there.

I've done this kind of scripting in the build config for the requirejs-rails gem. Here's an example gist that shows what r.js would see at build time.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top