sighol
sighol

Reputation: 2818

How to optimize all javascript files in a directory with requirejs

I have a folder structure like this:

.
├── autocomplete
│   ├── core.js
│   ├── search.js
│   └── user.js
├── build.js
├── collapsible_lists.js
├── griffgrabber
│   ├── canvasobject.js
│   ├── cargame.js
│   ├── car.js
│   ├── griffDrawer.js
│   ├── keylistener.js
│   ├── run.js
│   └── victim.js
├── main.js
├── newsfeed.js
├── require.js
├── shortcut.js
└── sidebar.js

3 directories, 20 files

main.js is the startup file. That file requires a couple of the files, but not all of them. The rest of the files are included with

<script>
    require(['shortcut'], function(shortcut){
        // ...
    })
</script>

in some html files.

This is my build.js file so far:

{
    baseUrl: ".",
    name: "main",
    out: "main-built.js",
}

But it only includes the files that are required by main.js. Is it possible to optimize all the javascript files in one run?

Upvotes: 4

Views: 1953

Answers (3)

kryger
kryger

Reputation: 13181

(to expand @Ryan Lynch's suggestion):

Use the include option, as per the documentation:

You can always explicitly add modules that are not found via the optimizer's static analysis by using the include option.

(http://requirejs.org/docs/optimization.html)

{
    baseUrl: ".", // ?
    appDir: ".", // ?
    dir: "output/",
    modules: [
        {
            name: "main",
            include: [ "shortcut" ]
        }
    ]
}

More detailed example in the excellent example.build.js (I actually find it more useful than the documentation page)


(sorry, had no time to replicate and test properly to make sure the paths values are correct, I'll try that later and update my answer)

Upvotes: 1

kryger
kryger

Reputation: 13181

Another - less orthodox - way of achieving this would be to add this "shortcut" module as a dependency to any of the "visible" modules that are discovered by r.js scanning (i.e. "main.js"). This way the entire dependency branch starting at "shortcut" would be included in the output.

Upvotes: 0

Ryan Lynch
Ryan Lynch

Reputation: 7776

Try including a modules array in your options, so:

{
    baseUrl: ".",
    out: "main-built.js",
    modules: [
        {
            name: "main"
        }
    ]
}

As per the documentation:

In the modules array, specify the module names that you want to optimize, in the example, "main". "main" will be mapped to appdirectory/scripts/main.js in your project. The build system will then trace the dependencies for main.js and inject them into the appdirectory-build/scripts/main.js file.

Upvotes: 0

Related Questions