Require.js optimizer and variables in paths

2019-04-09 15:51发布

问题:

I have a problem getting r.js to work the way we need it to.

I have the following problem: We have 2 domains (e.g. foo.de and bar.de) and different environments. Depending on what environment and what domain they are running on they need to load a different file from their origin servers. My initial solution was this:

// channelDomain and environmentPath get defined above this script
require.config({
  paths: {
    'fooscript': channelDomain+environmentPath
  }
}

Testing this in the browser unoptimized works exactly as it should but the nightly build complained with:

[Error: Error: The config in mainConfigFile /absolute/path/app/public/js/main.js 
cannot be used because it cannot be evaluated correctly while running in the 
optimizer. Try only using a config that is also valid JSON, or do not use 
mainConfigFile and instead copy the config values needed into a build file or 
command line arguments given to the optimizer.
Source error from parsing: /absolute/path/app/public/js/main.js: ReferenceError:
channelDomain is not defined

I tried doing lots of things but I'm running out of ideas. I tried doing the empty: thing in the build file but that didn't work either. I'd be glad if someone could point me into the right direction.

回答1:

Use two require.config in the same file. The optimizer will only read the first one, as James says here https://github.com/jrburke/r.js/issues/270#issuecomment-13112859, and it will work in the browser after optimization.

So at the end you will have something like this in main.js:

require.config({
    //only configurations needed for the transpiler's optimization
});

require.config({
  paths: {
    'fooscript': channelDomain+environmentPath
  }
});