javascript – How to get some js-code separately as a code, separately as a string?


I am writing an application to document some internal framework. This application should have, among other things, two sections:

Section one, source code configuring some of our components, something like:

var MegaComponent = new core.form.awesomeThings.SuperComponent({
                    model: this.model,
                    someProperty: true,
                    otherProperty: 'blahblah',
                    yetAnotherProperty: {}

Section two, the actual visual display of a component with such properties. That is, what happens if we create a megacomponent and drop it onto our mold.

Actually, in essence, this and that is practically one essence. And if we want to change something in the configuration of our component, it would be cool to do it in one place, and not separately go into the script, separately into the html-template.

That is, in the end, we need to either execute the code from a string, or get some piece of code as a string from itself, or organize some kind of system to pull the code separately as code and separately as text.

The question is: are there any approaches to solving such a problem that I have not thought about?

If it helps, then the application is a SPA on Backbone.Marionette beaten into require modules and uses handlebars as a template engine.

The options I came up with:

It is possible to store code examples in some large template / many small ones, render it, pull in its insides and turn them into executable code using eval .

However, you can probably store it not in a template, but in separate script files, pull them in ajax and again, if necessary.

I don’t like the option to "wrap it in a function" and make it toString , because, firstly, the minifier will shred it, and secondly, toString can gobble up the formatting of the code.


I solved it like this:

With the text plugin for requirejs, you can safely load files as text using the text! prefix text! This is usually used to load html-templates, but he also understands js-files and can load without executing. Then the content can be run through eval .

    function(testcase) {
Scroll to Top