Switch out of optimized code with require js at run time

时间:2016-04-04 16:42:37

标签: javascript requirejs

We are considering integrating our (large) web app with require js.

Currently, we optimize (concatenate and minify) our js files for production. In our environment at production runtime, we allow for a session level "debug" flag that can be secretly entered via the browser. When that flag is set, the browser loads the non-minified versions of the files (by use of a if/else statement in razor code) for debugging.

Is there a equivalent possible mechanism when working with require js?

In summary; we would like to use optimized js files at runtime using require js. We would also like the ability to load non-minified files at runtime based on a session state debug flag.

thanks in advance, -Marc

1 个答案:

答案 0 :(得分:2)

we would like to use optimized js files at runtime using require js. We would also like the ability to load non-minified files at runtime

This is best done by using source maps instead. If a source map is present for a minified file, the browser can use it to translate your minified code back into the raw version on the fly without having to have the actual raw code present.

Minifiers have the option to generate source maps along with minified code. RequireJS optimizer, afaik, uses Uglify2 which can generate source maps.

Source maps are good especially in pre-production environments. Should you want to disable this ability, like in production, just don't deploy the source map files.

In our environment at production runtime, we allow for a session level "debug" flag that can be secretly entered via the browser.

By the way, this is a terrible idea. This setup is just overhead and code cruft.


If you really insist on loading the raw source for debugging purposes and the compiled version for production, you can simply swap out the compiled script with the entrypoint script of the uncompiled code. This assumes you have both versions, raw and compiled, on the server.

In the following example (PHP), assuming main.js is the entrypoint script of the raw source, main.min.js is the compiled version, and $debug is some value telling the server what mode you're using, you can simply do:

<script src="path/to/require.js"></script>

<? if($debug): ?>
<script src="path/to/main.js"></script>
<? else: ?>
<script src="path/to/main.min.js"></script>
<? endif; ?>

Do note, however, that raw source may act differently from one that's compiled. Minifiers have the tendency to take unexpected shortcuts and make assumptions on your code. This may cause raw and compiled versions to differ in behavior.