builders Object

Static Methods

    alias(aliases: Object) -> Directive

    Define aliases for modules.

    Parameters (1)

    aliases
    Object

    Mapping of aliases. Keys must be the names of modules as they appear in require (or import) statements and may be suffixed by $ to make the alias usable only when the path ends with the key.

    The values are paths to the modules that should be used instead.

    Return Value

    Directive

      Examples

      b.alias({
        // turn require("foo") into require("bar")
        'foo': 'bar',
      
        // turn:
        //      require("react/addons")
        //      require("react/addons/x")
        // into:
        //      require("react-addons-test-utils")
        //      require("react/addons/x")
        'react/addons$': 'react-addons-test-utils'
      })

    aliasLoader(aliases: Object) -> Directive

    Like builders.alias but for loaders.

    Parameters (1)

    aliases
    Object

    Return Value

    Directive

    compile(options: Object) -> Directive

    Compile files using a list of "loaders".

    Parameters (7)

    options
    Object
    options.pattern
    RegExp

    See FileTypes for pre-defined matchers you can utilize.

    options.loaders
    Array.<Directive>

    List of "loader directives" generated by builders.loader.

    options.include
    Array.<FilePattern>

    List of patterns to apply the loaders to.

    options.exclude
    Array.<FilePattern>

    List of patterns to exclude.

    options.enableHappyPack
    Boolean

    Enable this if you want to use happypack for parallel compilation.

    Defaults to: false

    options.useSingleLoader
    Boolean

    Set this to true if you're using ExtractTextPlugin.extract().

    Please note that HappyPack will not be honored if this option is enabled.

    Defaults to: false

    Return Value

    Directive

    compileHTML(options: Object) -> Directive

    Generate an HTML file using html-webpack-plugin if it is available.

    The plugin is expected to be installed otherwise an invariant violation error will be thrown at compose time!

    Parameters (1)

    options
    Object

    Options to pass to the plugin. Refer to its documentation.

    Return Value

    Directive

      Examples

      // @file: webpack.config.js
      b.compileHTML({
        template: path.resolve(__dirname, 'src/index.html'),
        filename: path.resolve(__dirname, 'dist/index.html')
      })
      
      // @file: src/index.html
      <body>
        <% if (process.env.NODE_ENV === 'test') { %>
          <script src="/dist/tests.js"></script>
        <% } else { %>
          <script src="/dist/app.js"></script>
        <% } %>
      </body>

    context(directory: String) -> Directive

    Set the "context" directory from which modules will be resolved (this also applies to DLLs unless explicitly overridden.)

    When unset, webpack defaults to process.cwd() which is not always a good idea.

    Parameters (1)

    directory
    String

    Absolute path to a directory. Make sure you use path.resolve() or something similar!

    Return Value

    Directive

      Examples

      // hierarchy:
      //
      // | node_modules
      // | src
      // | --- | a.js
      // | --- | b.js
      // | webpack.config.js
      b.context(path.resolve(__dirname))
      
      // hierarchy:
      //
      // | node_modules
      // | src
      // | --- | a.js
      // | --- | b.js
      // | webpack
      // | ------- | config.js
      b.context(path.resolve(__dirname, '..'))

    defineConstants(definitions: Object) -> Directive

    Define runtime constants that can be used by modules in the bundle. A popular example is exposing process.env.NODE_ENV to branch between environments, barring opinions.

    Parameters (1)

    definitions
    Object

    Mapping of definitions. Keys are the identifiers that will be exposed to modules and the values are the values to assign to those identifiers.

    Note that mortal-webpack will call JSON.stringify() on those values so you don't need to.

    Return Value

    Directive

      Examples

      b.defineConstants({
        'process.env.NODE_ENV': process.env.NODE_ENV,
        '__TEST__': process.env.NODE_ENV === 'test'
      })
      
      // in your module
      if (process.env.NODE_ENV === 'development') {
        // ...
      }
      else if (__TEST__) {
        // ...
      }

    defineExternalModules(externals: Object) -> Directive

    Define a mapping of modules to be considered "external" and not be served by webpack (at least not in this build.)

    Refer to the upstream externals documentation for more information about this.

    Parameters (1)

    externals
    Object

    Return Value

    Directive

      Examples

      Use jQuery from window instead of npm - do not include it in the build:

      b.defineExternalModules({
        'jquery': 'jQuery'
      })
      
      // in your source modules, the following two statements are
      // equivalent:
      const $ = require('jquery')
      const $ = window.jQuery

    devTool(tool: String) -> Directive

    Specify the "dev tool" to use in the resulting bundle.

    Parameters (1)

    tool
    String

    One of the valid dev-tools webpack understands.

    Return Value

    Directive

    disableNodeShims() -> Directive

    Disable webpack's shimming of "node" features like __dirname and Buffer.

    Currently this isn't configurable and only disables the Buffer shim.

    Return Value

    Directive

    dontEmitOnError() -> Directive

    Instruct webpack not to generate any bundle if a module error occurs. This is useful in production builds because you really don't want a broken bundle. However, in development (assuming you're using --watch) it's okay since you don't want to re-run webpack on every failure.

    Return Value

    Directive

    dontParse(patterns: Array.<FilePattern>) -> Directive

    Exclude files from being processed by any loader even if their rules match.

    This is useful for source files that are either already pre-processed (e.g. "dist" files in npm modules) or for legacy files that make webpack go crazy.

    An additional use I found for this directive is to gain some speed; really large vendor files (Ember? ._.) tend to take a gross amount of time to process, so if you can find a pre-processed version of those modules you may spare yourself some boredom.

    Parameters (1)

    patterns
    Array.<FilePattern>

    Return Value

    Directive

      Examples

      Don't parse any file under a directory named "vendor"; just use them as-is.

      b.dontParse([ new RegExp('vendor/') ])

    enableDevServer(params: Object) -> Directive

    Configure webpack dev server. This directive will take care of rewiring output.publicPath so that it includes the dev server host that you specify.

    Note that this does not add the dev middleware or anything; it assumes you're using the webpack-dev-server binary instead.

    Parameters (2)

    params
    Object
    params.host
    String!

    The host of the dev server, like http://localhost:9090.

    Return Value

    Directive

    ensureEnv(env: String) -> Directive

    Break the build if process.env.NODE_ENV is not set to the expected value. This is a common issue where the code relies on that variable and the user (or a script) forgets to set it.

    Internally, this ends up calling builders.invariant to perform the check so the behaviour is similar to it.

    Parameters (1)

    env
    String

    A NODE_ENV value, like "development", that you want to ensure.

    Return Value

    Directive

      Examples

      b.ensureEnv('test')
      $ webpack
      # ERROR Target requires NODE_ENV to be set to "test" ...
      
      $ NODE_ENV=test webpack
      # OK

    generateBundle() -> Directive

    Generate a bundle from a bunch of modules. This maps to webpack's entry points.

    Parameters (2)

    options.name
    String

    A name for the bundle which may be utilized in the output by the [name] interpolation pattern.

    options.modules
    Array.<String>

    Paths to the modules that the bundle should contain.

    Return Value

    Directive

    generateCommonBundle() -> Directive

    Generate a bundle like in builders.generateBundle except that this one is meant to be the "common" bundle that includes modules referenced by one or more other bundles.

    Commonly this is referred to as the "vendor" or "commons" bundle. Or chunk. Whatever confuses you more.

    Parameters (4)

    options.name
    String
    options.modules
    Array.<String>
    options.strict
    Boolean

    Only allow the modules referenced in the "modules" parameter to show up in the bundle. This is the default mortal-webpack behaviour but it is not the default webpack behaviour.

    Internally, it does this by setting the minChunks plugin option to Infinity.

    More information can be found in the common bundles guide.

    Defaults to: true

    options.pluginOptions
    Object

    Override options on the underlying plugin directly.

    Defaults to: {}

    Return Value

    Directive

      Examples

      Say you split your application modules into three bundles as such:

      1. "guest"
      2. "member"
      3. "admin"

      However, they all use some common dependencies like "lodash", so you'd end up defining "lodash" to be a member of a common bundle that will then be available for all 3 bundles above:

      c.generateCommonBundle({ name: 'vendor', modules: [ 'lodash' ] })
      c.generateBundle({ name: 'guest', modules: [ './src/guest.js' ] })
      c.generateBundle({ name: 'member', modules: [ './src/member.js' ] })
      c.generateBundle({ name: 'admin', modules: [ './src/admin.js' ] })

      Note

      It makes sense to have only one common bundle in a build, and mortal-webpack currently performs no checks to ensure that to be the case, so act with responsibility please unless you know what you're doing!

    generateDLL() -> Directive

    Generate a bundle that can be used as a DLL.

    Parameters (4)

    options.path
    String

    Path to where the DLL's "manifest" will be generated. This file is needed by webpack when it wants to reference this DLL.

    It is safe not to track this file in source control.

    options.name
    String

    A name for the generated bundle. You can use this for interpolation in output and other places where [name] is interpolated.

    options.modules
    Array.<String>

    The modules to include in the bundle. This is similar to the parameter in builders.generateBundle.

    options.libraryName
    String

    An "identifier" for the function exported by the bundle. This is for internal use by webpack and has to match the "output.libraryName", which mortal-webpack will do implicitly for you.

    If you leave this blank, we will define it as:

    dll_[name]_[hash]

    See the reference page for more information.

    Return Value

    Directive

      Examples

      c.generateDLL({
        path: path.resolve(__dirname, 'tmp/dll-manifests/vendor.json'),
        name: 'ApplicationVendorDLL',
        modules: [
          'lodash',
          'react'
        ]
      })

    generateSourceMaps() -> Directive

    Generate source maps for your bundles. If you're also optimizing it will instruct UglifyJS to output source maps.

    Return Value

    Directive

    instrumentJS() -> Array.<Directive>

    Collect coverage information from JavaScript modules using istanbul.

    The parameters are akin to those required by builders.compile since this ends up generating a loader as well (or well, something like that anyway.)

    Parameters (4)

    options.pattern
    RegExp

    See FileTypes for pre-defined file matchers.

    options.loader
    String

    Path to the instrumenting loader. If you don't know what this is, see Coverage with Istanbul for a sample implementation.

    options.include
    Array.<FilePattern>

    List of file patterns to instrument.

    options.exclude
    Array.<FilePattern>

    List of file patterns to exclude from instrumenting. Those would not count towards the coverage.

    Return Value

    Array.<Directive>

    The first directive will set the runtime constant process.env.COVERAGE to 1 in case you need it. The second one will install the instrumenting loader.

    invariant(predicate: Boolean|Function, message: String) -> Directive

    Break the build if a condition is not met. This is very useful to ensure that build parameters (environment variables or javascript ones) are what you expect them to be, like say process.env.NODE_ENV.

    If the invariant does not hold, compose will return an instance of the InvalidConfig class instead of the configuration object.

    Parameters (2)

    predicate
    Boolean|Function
    message
    String

    A message to present to the user in case the invariant does not hold.

    Return Value

    Directive

      Examples

      This shows how we can ensure that the COVERAGE environment variable is either not set or if it is, the value is valid (which is the string "1"):

      b.invariant(!process.env.COVERAGE || process.env.COVERAGE === '1',
        "COVERAGE environment variable must either be unset" +
        "or set to '1'."
      )

    loader(params: Object) -> Directive

    Construct a "loader" directive for use by builders.compile. This helper is preferred over defining loaders directly so that mortal-webpack can choose the correct notation based on webpack's version and whether happypack is in use or not.

    Parameters (4)

    params
    Object
    params.name
    String

    Name of the loader module, like babel-loader for example.

    params.options
    Object

    JSON-serializable set of loader options (or "query" as it's been called in webpack-1)

    params.enabled
    Boolean

    Set this to false if you want to conditionally exclude this loader. This is a convenience option.

    Return Value

    Directive

    For use in the loaders parameter required by builders.compile.

    message(message: String) -> Directive

    Print a message to standard out. Useful for informing the user of conditional directives (for example, whether coverage is enabled.)

    Parameters (1)

    message
    String

    Return Value

    Directive

    optimizeJS(uglifyOptions: Object) -> Directive

    Optimize the resulting bundles using uglifyJs.

    Parameters (1)

    uglifyOptions
    Object

    Options to pass to uglify. Refer to their webpage for what these may be.

    Return Value

    Directive

    output(options: Object) -> Directive

    Configure output parameters.

    Parameters (5)

    options
    Object
    options.filename
    String
    options.path
    String
    options.publicPath
    String

    This parameter will be adjusted in case you've enabled the dev server.

    options.library
    String

    This parameter will be overridden in case you're defining a DLL.

    Return Value

    Directive

    plugin(plugin: Object) -> Directive

    Add a custom plugin.

    Parameters (1)

    plugin
    Object

    The plugin to use, like new ExtractTextWebpackPlugin(...).

    Return Value

    Directive

    resolveLoaders() -> Directive

    Configure resolveLoader parameters for resolving loaders.

    Parameters (6)

    options.directories
    Array.<FilePattern>

    Maps to resolve.root

    options.relativeDirectories
    Array.<FilePattern>
    options.extensions
    Array.<FileExtension>
    options.fallbackDirectories
    Array.<FilePattern>

    Maps to resolve.fallback in webpack1.

    options.moduleTemplates
    Array.<String>
    options.packageMains
    Array.<String>

    Return Value

    Directive

    resolveModules() -> Directive

    Configure resolve parameters for resolving modules.

    A few parameters were renamed to be more meaningful and are listed below, otherwise the parameters are as they appear in webpack-1 documentation.

    To define resolving aliases, see builders.alias.

    Parameters (4)

    options.directories
    Array.<FilePattern>

    Maps to resolve.root

    options.relativeDirectories
    Array.<FilePattern>
    options.extensions
    Array.<FileExtension>
    options.fallbackDirectories
    Array.<FilePattern>

    Maps to resolve.fallback in webpack1.

    Return Value

    Directive

    sortBundleModules() -> Directive

    Use the occurrence order plugin to sort the resulting modules in the bundle and make the output consistent between different runs.

    Return Value

    Directive

    unless(predicate: Boolean|Function, directives: Array.<Directive>) -> Array.<Directive>

    Apply directives unless a predicate holds true. This is the complement of builders.when.

    Parameters (2)

    predicate
    Boolean|Function
    directives
    Array.<Directive>

    Return Value

    Array.<Directive>

      Examples

      b.unless(process.env.USE_SOURCE_MAPS === '1', [
        b.devTool('eval')
      ])

    use(profile: Array.<Directive>) -> Array.<Directive>

    Use a set of directives. This can be utilized to create composite targets.

    Parameters (1)

    profile
    Array.<Directive>

    Return Value

    Array.<Directive>

      Examples

      const baseTarget = [
        b.alias({ foo: 'bar' })
      ]
      
      const developmentTarget = [
        b.use(baseTarget),
      
        b.alias({ bar: 'baz' })
      ]

    useDLL() -> Directive

    Use a pre-built DLL.

    Parameters (2)

    options.path
    String

    Path to the dll's manifest. This corresponds to the path parameter you passed when you've defined the DLL.

    options.context
    String?

    The directory from which the files defined in that manifest should be resolved from. This defaults to the context webpack was run in if you leave it out.

    Return Value

    Directive

    watch(watchOptions: Object) -> Directive

    Configure webpack's watcher. This is useful to tune if you're coupling webpack with, say, Karma for tests.

    This will set config.watch to true and define the options on config.watchOptions for webpack-dev-middleware.

    Parameters (3)

    watchOptions
    Object
    watchOptions.aggregateTimeout
    Number

    Defaults to: 300

    watchOptions.poll
    Boolean

    Defaults to: true

    Return Value

    Directive

    when(predicate: Boolean|Function, directives: Array.<Directive>) -> Array.<Directive>

    Apply directives if a predicate holds true.

    Parameters (2)

    predicate
    Boolean|Function
    directives
    Array.<Directive>

    Return Value

    Array.<Directive>

      Examples

      b.when(process.env.USE_SOURCE_MAPS === '1', [
        b.devTool('source-map')
      ])

    whenEnv(env: String, directives: Array.<Directive>) -> Array.<Directive>

    Apply directives only in a specific "node" environment. This is equivalent to calling builders.when with a predicate against process.env.NODE_ENV.

    Parameters (2)

    env
    String

    The desired value of process.env.NODE_ENV, like "test".

    directives
    Array.<Directive>

    Return Value

    Array.<Directive>

      Examples

      b.env('development', [
        b.devTool('eval'),
        b.enableDevServer({ ... })
      ])
      
      b.env('production', [
        b.devTool('source-map')
      ])

Type Definitions

    Directive

    A directive is the internal representation of a configuration directive. You do not create or interact with these constructs directly. Instead, you are expected to generate them using the builder APIs and pass them to compose to generate the resulting configuration.

    Directives are plain objects (POJOs).

    name: String

    A unique name that describes this directive.

    params: Any?

    Any parameters needed for applying this directive.

    FileExtension

    A string representing a file extension with the leading dot. An "empty" file extension is required for webpack-1 in order to resolve files with a specific extension.

    Example values:

    ""
    ".js"
    ".css"

    FilePattern

    A string pointing to either a directory or to a specific file.