Giter Club home page Giter Club logo

babel-loader's Introduction

This README is for babel-loader v8/v9 with Babel v7 If you are using legacy Babel v6, see the 7.x branch docs

NPM Status codecov

Babel Loader

This package allows transpiling JavaScript files using Babel and webpack.

Note: Issues with the output should be reported on the Babel Issues tracker.

Install

babel-loader supported webpack versions supported Babel versions supported Node.js versions
8.x 4.x or 5.x 7.x >= 8.9
9.x 5.x ^7.12.0 >= 14.15.0
npm install -D babel-loader @babel/core @babel/preset-env webpack

Usage

webpack documentation: Loaders

Within your webpack configuration object, you'll need to add the babel-loader to the list of modules, like so:

module: {
  rules: [
    {
      test: /\.(?:js|mjs|cjs)$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: [
            ['@babel/preset-env', { targets: "defaults" }]
          ]
        }
      }
    }
  ]
}

Options

See the babel options.

You can pass options to the loader by using the options property:

module: {
  rules: [
    {
      test: /\.(?:js|mjs|cjs)$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: [
            ['@babel/preset-env', { targets: "defaults" }]
          ],
          plugins: ['@babel/plugin-proposal-class-properties']
        }
      }
    }
  ]
}

This loader also supports the following loader-specific option:

  • cacheDirectory: Default false. When set, the given directory will be used to cache the results of the loader. Future webpack builds will attempt to read from the cache to avoid needing to run the potentially expensive Babel recompilation process on each run. If the value is set to true in options ({cacheDirectory: true}), the loader will use the default cache directory in node_modules/.cache/babel-loader or fallback to the default OS temporary file directory if no node_modules folder could be found in any root directory.

  • cacheIdentifier: Default is a string composed by the @babel/core's version, the babel-loader's version, the contents of .babelrc file if it exists, and the value of the environment variable BABEL_ENV with a fallback to the NODE_ENV environment variable. This can be set to a custom value to force cache busting if the identifier changes.

  • cacheCompression: Default true. When set, each Babel transform output will be compressed with Gzip. If you want to opt-out of cache compression, set it to false -- your project may benefit from this if it transpiles thousands of files.

  • customize: Default null. The path of a module that exports a custom callback like the one that you'd pass to .custom(). Since you already have to make a new file to use this, it is recommended that you instead use .custom to create a wrapper loader. Only use this if you must continue using babel-loader directly, but still want to customize.

  • metadataSubscribers: Default []. Takes an array of context function names. E.g. if you passed ['myMetadataPlugin'], you'd assign a subscriber function to context.myMetadataPlugin within your webpack plugin's hooks & that function will be called with metadata.

Troubleshooting

babel-loader is slow!

Make sure you are transforming as few files as possible. Because you are probably matching /\.m?js$/, you might be transforming the node_modules folder or other unwanted source.

To exclude node_modules, see the exclude option in the loaders config as documented above.

You can also speed up babel-loader by as much as 2x by using the cacheDirectory option. This will cache transformations to the filesystem.

Some files in my node_modules are not transpiled for IE 11

Although we typically recommend not compiling node_modules, you may need to when using libraries that do not support IE 11 or any legacy targets.

For this, you can either use a combination of test and not, or pass a function to your exclude option. You can also use negative lookahead regex as suggested here.

{
    test: /\.(?:js|mjs|cjs)$/,
    exclude: {
      and: [/node_modules/], // Exclude libraries in node_modules ...
      not: [
        // Except for a few of them that needs to be transpiled because they use modern syntax
        /unfetch/,
        /d3-array|d3-scale/,
        /@hapi[\\/]joi-date/,
      ]
    },
    use: {
      loader: 'babel-loader',
      options: {
        presets: [
          ['@babel/preset-env', { targets: "ie 11" }]
        ]
      }
    }
  }

Babel is injecting helpers into each file and bloating my code!

Babel uses very small helpers for common functions such as _extend. By default, this will be added to every file that requires it.

You can instead require the Babel runtime as a separate module to avoid the duplication.

The following configuration disables automatic per-file runtime injection in Babel, requiring @babel/plugin-transform-runtime instead and making all helper references use it.

See the docs for more information.

NOTE: You must run npm install -D @babel/plugin-transform-runtime to include this in your project and @babel/runtime itself as a dependency with npm install @babel/runtime.

rules: [
  // the 'transform-runtime' plugin tells Babel to
  // require the runtime instead of inlining it.
  {
    test: /\.(?:js|mjs|cjs)$/,
    exclude: /node_modules/,
    use: {
      loader: 'babel-loader',
      options: {
        presets: [
          ['@babel/preset-env', { targets: "defaults" }]
        ],
        plugins: ['@babel/plugin-transform-runtime']
      }
    }
  }
]

NOTE: transform-runtime & custom polyfills (e.g. Promise library)

Since @babel/plugin-transform-runtime includes a polyfill that includes a custom regenerator-runtime and core-js, the following usual shimming method using webpack.ProvidePlugin will not work:

// ...
        new webpack.ProvidePlugin({
            'Promise': 'bluebird'
        }),
// ...

The following approach will not work either:

require('@babel/runtime/core-js/promise').default = require('bluebird');

var promise = new Promise;

which outputs to (using runtime):

'use strict';

var _Promise = require('@babel/runtime/core-js/promise')['default'];

require('@babel/runtime/core-js/promise')['default'] = require('bluebird');

var promise = new _Promise();

The previous Promise library is referenced and used before it is overridden.

One approach is to have a "bootstrap" step in your application that would first override the default globals before your application:

// bootstrap.js

require('@babel/runtime/core-js/promise').default = require('bluebird');

// ...

require('./app');

The Node.js API for babel has been moved to babel-core.

If you receive this message, it means that you have the npm package babel installed and are using the short notation of the loader in the webpack config (which is not valid anymore as of webpack 2.x):

  {
    test: /\.(?:js|mjs|cjs)$/,
    loader: 'babel',
  }

webpack then tries to load the babel package instead of the babel-loader.

To fix this, you should uninstall the npm package babel, as it is deprecated in Babel v6. (Instead, install @babel/cli or @babel/core.) In the case one of your dependencies is installing babel and you cannot uninstall it yourself, use the complete name of the loader in the webpack config:

  {
    test: /\.(?:js|mjs|cjs)$/,
    loader: 'babel-loader',
  }

Exclude libraries that should not be transpiled

core-js and webpack/buildin will cause errors if they are transpiled by Babel.

You will need to exclude them form babel-loader.

{
  "loader": "babel-loader",
  "options": {
    "exclude": [
      // \\ for Windows, / for macOS and Linux
      /node_modules[\\/]core-js/,
      /node_modules[\\/]webpack[\\/]buildin/,
    ],
    "presets": [
      "@babel/preset-env"
    ]
  }
}

Top level function (IIFE) is still arrow (on Webpack 5)

That function is injected by Webpack itself after running babel-loader. By default Webpack asumes that your target environment supports some ES2015 features, but you can overwrite this behavior using the output.environment Webpack option (documentation).

To avoid the top-level arrow function, you can use output.environment.arrowFunction:

// webpack.config.js
module.exports = {
  // ...
  output: {
    // ...
    environment: {
      // ...
      arrowFunction: false, // <-- this line does the trick
    },
  },
};

Customize config based on webpack target

Webpack supports bundling multiple targets. For cases where you may want different Babel configurations for each target (like web and node), this loader provides a target property via Babel's caller API.

For example, to change the environment targets passed to @babel/preset-env based on the webpack target:

// babel.config.js

module.exports = api => {
  return {
    plugins: [
      "@babel/plugin-proposal-nullish-coalescing-operator",
      "@babel/plugin-proposal-optional-chaining"
    ],
    presets: [
      [
        "@babel/preset-env",
        {
          useBuiltIns: "entry",
          // caller.target will be the same as the target option from webpack
          targets: api.caller(caller => caller && caller.target === "node")
            ? { node: "current" }
            : { chrome: "58", ie: "11" }
        }
      ]
    ]
  }
}

Customized Loader

babel-loader exposes a loader-builder utility that allows users to add custom handling of Babel's configuration for each file that it processes.

.custom accepts a callback that will be called with the loader's instance of babel so that tooling can ensure that it using exactly the same @babel/core instance as the loader itself.

In cases where you want to customize without actually having a file to call .custom, you may also pass the customize option with a string pointing at a file that exports your custom callback function.

Example

// Export from "./my-custom-loader.js" or whatever you want.
module.exports = require("babel-loader").custom(babel => {
  // Extract the custom options in the custom plugin
  function myPlugin(api, { opt1, opt2 }) {
    return {
      visitor: {},
    };
  }

  return {
    // Passed the loader options.
    customOptions({ opt1, opt2, ...loader }) {
      return {
        // Pull out any custom options that the loader might have.
        custom: { opt1, opt2 },

        // Pass the options back with the two custom options removed.
        loader,
      };
    },

    // Passed Babel's 'PartialConfig' object.
    config(cfg, { customOptions }) {
      if (cfg.hasFilesystemConfig()) {
        // Use the normal config
        return cfg.options;
      }

      return {
        ...cfg.options,
        plugins: [
          ...(cfg.options.plugins || []),

          // Include a custom plugin in the options and passing it the customOptions object.
          [myPlugin, customOptions],
        ],
      };
    },

    result(result) {
      return {
        ...result,
        code: result.code + "\n// Generated by some custom loader",
      };
    },
  };
});
// And in your Webpack config
module.exports = {
  // ..
  module: {
    rules: [{
      // ...
      loader: path.join(__dirname, 'my-custom-loader.js'),
      // ...
    }]
  }
};

customOptions(options: Object): { custom: Object, loader: Object }

Given the loader's options, split custom options out of babel-loader's options.

config(cfg: PartialConfig, options: { source, customOptions }): Object

Given Babel's PartialConfig object, return the options object that should be passed to babel.transform.

result(result: Result): Result

Given Babel's result object, allow loaders to make additional tweaks to it.

License

MIT

babel-loader's People

Contributors

couto avatar danez avatar dependabot[bot] avatar evilebottnawi avatar existentialism avatar gaearon avatar greenkeeper[bot] avatar hawkrives avatar hiroppy avatar hzoo avatar jedwards1211 avatar jlhwung avatar joshwiens avatar jupl avatar lencioni avatar loganfsmyth avatar michael-ciniawsky avatar nicolo-ribaudo avatar pierreneter avatar piperchester avatar piwysocki avatar popuguytheparrot avatar sebmck avatar shinnn avatar sibiraj-s avatar strml avatar tricknotes avatar turbo87 avatar xtuc avatar yuyokk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

babel-loader's Issues

"Uncaught TypeError: Cannot read property 'Object' of undefined" after upgrade to Babel 5.0

Babel Versions

  • babel-core: 5.0.12
  • babel-runtime: 5.0.12
  • babel-loader: 5.0.0

It seems like it might be an issue where the babel-runtime is not being bundled in properly

Everything works fine if compiled with babel < 5.0
Not sure if the modules I am using are causing the problem since they where compiled with a babel version < 5.0

Modules Precompiled w/ Babel < 5.0

react-gestures
gmaps-places-autocomplete
cync

Browser Error

Uncaught TypeError: Cannot read property 'Object' of undefined
file: ./~/babel-runtime/~/core-js/library/modules/$.js

screen shot 2015-04-09 at 11 58 12 am

Webpack Config

var webpack = require('webpack')
  , path = require('path')
  , WebpackDevServer = require('webpack-dev-server')
  , CommonChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');

var commonPlugin = new CommonChunkPlugin('vendor', 'vendor.bundle.js');

// Simple dev / production switch
function _env(dev, production) {
  return process.env.BUILD_ENV === 'production' ? production : dev;
}

function _path(p) {
  return path.join(__dirname, p);
}

var compiler = module.exports = {
  plugins: [commonPlugin],
  devtool: _env('eval', false),
  entry: {
    app: _path('src/index.js'),
    vendor: ['superagent','react','immutable', 'google']
  },
  output: {
    path: _path('www'),
    filename: 'bundle.js', //this is the default name, so you can skip it
  },
  module: {
    loaders: [
      { test: /\.(js|jsx)$/, loader: 'babel-loader?stage=1&optional=runtime', exclude:['node_modules'] },
      { test: /\.(css|less)$/, loader: 'style-loader!css-loader?' + _env('sourceMap=1&', '') + 'importLoaders=1!autoprefixer' },
      { test: /\.(png|jpg|jpeg|gif)$/, loader: 'url?limit=8192'},
      { test: /\.(eot|woff|ttf|svg)$/, loader: 'url?limit=8192'}
    ]
  },
  externals: _env({
    react: 'React',
    immutable: 'Immutable',
    google: 'google'
  },{ google: 'google'}),
  resolve: {
    alias: {
      superagent: 'superagent/lib/client'
    },
    extensions: ['', '.css', '.react.js', '.js', '.jsx']
  }
};


if (process.env.BUILD_ENV !== 'production') {
  var server = new WebpackDevServer(webpack(compiler), {
    hot: false,
    quiet: false,
    noInfo: false,
    filename: "bundle.js",
    contentBase: _path('src'),
    publicPath: "/",
    headers: { "X-Development-Build": true },
    stats: { colors: true },
    historyApiFallback: false,
  });
  server.listen(8090, "localhost", function() {});
}

[bug] Strange compilation of ES6 `import`

With this versions ([email protected])

"dependencies": {
  "babel-core": "5.1.10",
  "babel-loader": "4.3.0",
  "webpack": "1.8.5"
}
$ git clone [email protected]:AlexKVal/bug_babel_webpack.git
$ npm istall

this code client.js

import plugin from './client_plugin';
console.log("hello " + plugin.p)

compiles OK

$ webpack

into this code bundle.js

var plugin = _interopRequire(__webpack_require__(1));
console.log("hello " + plugin.p);

But with the [email protected]

$ npm i [email protected]
$ webpack

it compiles into this bundle.js

var _plugin = __webpack_require__(1);
var _plugin2 = _interopRequireWildcard(_plugin);
console.log("hello " + _plugin2["default"].p);

And in that case if I run

eval('console.log("hello " + plugin.p)');

I've got a ReferenceError cannot find "plugin"

Webpack config:

module.exports = {
  entry: "./client.js",
  output: {
    path: __dirname,
    filename: "bundle.js"
  },
  module: {
    loaders: [
      { test: /\.js/, loader: 'babel', exclude: /node_modules/ }
    ]
  }
};

Here is the trash project for bug reproducing.

Can't get runtime instructions to work

I'm following instructions on using a shared runtime and have this in my config:

  plugins: [
    new webpack.ProvidePlugin({
      to5Runtime: "imports?global=>{}!exports?global.to5Runtime!6to5/runtime"
    })
  ],
  module: {
    loaders: [
      { test: /\.jsx?$/, loader: '6to5?experimental&runtime', exclude: /node_modules/ },

6to5 works, but if I use e.g. spread operator:

var x = {a:1, b: 2};
var y = {...x};

I get a compile time error:

ERROR in ./src/scripts/organisms/Whatever.jsx
Module not found: Error: Cannot resolve module '6to5/runtime' in /Users/dan/Documents/Projects/whatever/src/scripts/organisms
 @ ./src/scripts/organisms/Whatever.jsx 1:0-68

Seems like ProvidePlugin works but there's no 6to5/runtime? I'm using trunk version of 6to5.

Note caveat: when using bluebird to alias Promise

Note dirty fix: babel/babel#630 (comment) (EDIT: see comments below)

This is probably a common use case in webpack.

If using selfContained option in 6to5 v3, and if one wants to use the bluebird library (or their favourite Promise lib), the following doesn't work nicely anymore:

// ...
        new webpack.ProvidePlugin({
            'Promise': 'bluebird'
        }),
// ...

Error in babel-loader 5.1.3

Lines 42 and 43 attempt to assign to undefined variables, which results in an error:

babel-loader/index.js

cacheDirectory = options.cacheDirectory;
cacheIdentifier = options.cacheIdentifier;

when changed to look like the following, everything starts to work again:

var cacheDirectory = options.cacheDirectory;
var cacheIdentifier = options.cacheIdentifier;

runtime file

Hello,
I think that loader must create runtime file and include it into dependencies. Now he adds a variety of methods, such _extend, in each file.

For example:
EError.js

class EError extends Error {
}

export default EError;

MyError,js

import EError from './EError.js';

class MyError extends EError {
}

export default MyError;

result bundle

/******/ (function(modules) { // webpackBootstrap
   < ..... >
/* 7 */
/*!*************************************************************************************!*\
  !***./MyError.js ***!
  \*************************************************************************************/
/***/ function(module, exports, __webpack_require__) {
    "use strict";

    var _extends = function(child, parent) {
      child.prototype = Object.create(parent.prototype, {
        constructor: {
          value: child,
          enumerable: false,
          writable: true,
          configurable: true
        }
      });

      child.__proto__ = parent;
    };

    var EError = __webpack_require__(/*! ./EError.js */ 8).default;

    var MyError= function(EError) {
      var MyError= function MyError() {
        EError.apply(this, arguments);
      };

      _extends(MyError, EError);
      return MyError;
    }(EError);

    exports.default = MyError;

/***/ },
/* 8 */
/*!*****************************************************************************!*\
  !*** ./EError.js ***!
  \*****************************************************************************/
/***/ function(module, exports, __webpack_require__) {
    "use strict";

    var _extends = function(child, parent) {
      child.prototype = Object.create(parent.prototype, {
        constructor: {
          value: child,
          enumerable: false,
          writable: true,
          configurable: true
        }
      });

      child.__proto__ = parent;
    };

    var EError = function(Error) {
      var EError = function EError(data) {
          if (data instanceof Error) return;

          if (data && data.message) {
              this.message = data.message;
          } else if (typeof data == 'string') {
              this.message = data;
          } else {
              this.message = this.constructor.name;
          }
      };

      _extends(EError, Error);
      return EError;
    }(Error);

    exports.default = EError;

/***/ },
  < .... >
/******/ ])

As you can see, the resulting file has a duplicate code.

It would be nice if the 6to5-loader did not create helper functions in each file, but instead include file with the runtime and use it.

Super slow

Is it typical for a build time for a small-ish site (only 80 JS modules) to take 30secs? Subsequent updates via watch are quick, but the initial build is a real killer.

5.1.0 cacheDirectory=true error

After upgrading to 5.1.0 I started getting the following error when I have cacheDirectory=true.

ERROR in ./src/main.jsx
Module build failed: Error: ENOENT, open 'true/994cacc0a9c148dedf802ed858d75ef521881c50.json.gzip'
    at Error (native)

I have removed everything from my main.jsx file except for one line, var x = 5;. If I remove the cacheDirectory=true everything seems to work, or if I downgrade to loader 5.0.0. I'm working on Mac OS 10.10.3.

Excluding node_modules but then what about 6to5 deps?

I don't understand the logic of excluding node_modules from 6to5 compile.

That means ES6-based modules to be compiled beforehand, which means a dep's deps cannot be shared across other deps' deps... This is bad.

Polyfill

Hi,

What is currently the best way to bundle the Babel polyfill when compiling bundles ? Shouldn't babel-loader do it automatically when using the experimental flag (or at least have an option to bundle it in the entry points) ?

I mainly ask because async functions do not work without the regenerator runtime.

Disabling source maps

How do I disable the source map that 6to5 generates, but allow the general webpack one?

Inconsistency with React's jsx-loader

Hello,

First of all thanks for the great library.
I am using Babel along with React & Webpack, and your loader is very handy.
There is a small inconsistency between React and babel-loader in using spread attributes in JSX.
If we take the following example:

var { checked, title, ...other } = this.props;
...
<input {...other}
        checked={checked}
        className={fancyClass}
        type="checkbox" />

In Babel I get the following error:
image

JSX support in README

Hello,

I am new to webpack and I was looking for a loader that would compile my ES6/JSX. There is no mention of having JSX support in your README. I think you should add it as it would be helpful to know for new comers to webpack looking to do the same.

Aside from that, thanks for the loader.

Compilation never finishes when using devtool: 'source-map'

I have a large project (~23 entry files) and I am using babel-loader. When I compile with "eval-source-map" it takes about 45 seconds to complete. When I use 'source-map' (for production builds), I canceled it after 2 hours. My project doesn't have many node_modules, mostly one large library that we do want to be transpiled.

hash current Babel options state to cache path

hi.

for example, I have .babelrc:

{
  "optional": [ "runtime", "asyncToGenerator" ],
  "blacklist": [ "regenerator" ],
  "stage": 0,
  "env": {
    "development": {
      "plugins": [ "typecheck" ]
    }
  }
}

and I keep getting the same cached version if I just want to rebuild my bundle from development env to production w/o any files changes.

rm babel-loader-* from require('os').tmpdir() helps once :)

so imo current options state needs to be stored somewhere here, but I can't figure out how to get it from babel to make a PR.

Mocking/stubbing dependencies in tests

I'm in the midst of a battle trying to support babel imports for niceness but also be able to stub out dependencies in tests.

Right now the only solution I can find that doesn't throw a giant wobbly in my webpack bundle is to use the inject-loader when importing files from tests. However - this only works with require syntax.

Are there any recommendations for stubbing out dependencies that are imported using babel-loader? Preferably having the only requirements being isolated to the test files themselves.

Build hangs

According to @darul75 on #74, his build hangs:

69% 311/312 build modules `

His config is:

{ test: /\.js?$/, loaders: ['react-hot', 'babel'], exclude: [/node_modules/, /__tests__/] },`

Feel free to add anything that I'm missing.

Stage 1 + "runtime" produces a bundle with cycles

Here's my webpack config:

module.exports = [
  {
    name: 'browser',
    entry: './web/index.js',
    output: {
      path: path.join(__dirname, 'build'),
      filename: 'bundle.js',
      publicPath: '',
    },
    module: {
      loaders: [
        {
          test: /\.js$/,
          exclude: '/node_modules/',
          loader: 'babel-loader',
          query: {
            stage: 1,
            optional: ['runtime'],
          },
        },
        { test: /\.css$/, loader: 'style-loader!css-loader' },
      ],
    },
  }
]

index.js contains one line: var React = require('react');

When the bundle.js is loaded in the browser, there's some exception that looks like it's due to a cycle where a module ends up requiring itself while it is still being initialized. Removing the "runtime" option fixes the bug.

regeneratorRuntime undefined

When using generator functions I the application throws with Uncaught ReferenceError: regeneratorRuntime is not defined.
It looks like the regeneratorRuntime does not get injected into the module somehow.

Array.findIndex not defined

I'm loading the babel-runtime, but Array.findIndex seems to not be shimmed. Am I doing something wrong here?

my loader configuration:

{ test: /.jsx?$/, loader: 'babel-loader?stage=0&optional[]=runtime', exclude: /(node_modules)|(bower_components)/ }

Error When leveraging Cache

When I set the cache directory I get the following stack trace:

Module build failed: Error: Final loader didn't return a Buffer or String
    at DependenciesBlock.onModuleBuild (/Users/Merrick/Developer/Domo/DomoWeb/DomoWeb/mobile-web/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:299:42)
    at nextLoader (/Users/Merrick/Developer/Domo/DomoWeb/DomoWeb/mobile-web/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:275:25)
    at /Users/Merrick/Developer/Domo/DomoWeb/DomoWeb/mobile-web/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:292:15
    at context.callback (/Users/Merrick/Developer/Domo/DomoWeb/DomoWeb/mobile-web/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:148:14)
    at /Users/Merrick/Developer/Domo/DomoWeb/DomoWeb/mobile-web/node_modules/babel-loader/index.js:58:7
    at /Users/Merrick/Developer/Domo/DomoWeb/DomoWeb/mobile-web/node_modules/babel-loader/lib/fs-cache.js:135:24
    at /Users/Merrick/Developer/Domo/DomoWeb/DomoWeb/mobile-web/node_modules/babel-loader/lib/fs-cache.js:40:14
    at Gunzip.onEnd (zlib.js:227:5)
    at Gunzip.emit (events.js:129:20)
    at _stream_readable.js:908:16

Any ideas? It works without cache just fine. :-)

Request: support for babel options as an object

I think webpack provide an API to accept any kind of option (query string or object) via the webpack instance .option[key] but I am not sure.
That being said, that could be great to define options like this

{
  //...
  babel: {
    experimental: true,
    playground: true,
    optional: [
      "runtime",
      "spec.protoToAssign",
    ],
    loose: "all",
  },
}

(And because query strings are so ugly)

Example of loader I made that use this simple way to read option:

https://github.com/MoOx/eslint-loader/blob/defe509dbb98e31d781dae35fa544c350730c411/index.js#L73
https://github.com/cssnext/cssnext-loader/blob/c7b79f5281a5e63adca933fc4ec434f965e686e3/index.js#L22

Feature Query: Filesystem Cache?

I work on a pretty big app and transpiling everything take a while on the first webpack build pass. Would you be open to a PR to add a filesystem cache to this module like babel/register does? I implemented it in a custom loader and for us, it reduces the initial build pass by ~20 seconds. I'd be happy to submit a PR to add it to the this as a optional flag.

Syntax Error in JSX crashes process

I'm using webpack-dev-server and babel-loader to compile a React application.

In babel-loader 5.1.0 and 5.1.2 syntax errors in JSX are causing the process to terminate after the error is logged.

I get the same behavior whether I use webpack-dev-server in my Node app or as a CLI.

In 5.0.0 I get the same stack trace but no process termination. Is there a new option to use or is this not desired?

Setting options

I get this error whenever I run webpack:

ERROR in ./src/client/app.jsx
Module build failed: ReferenceError: Unknown option: stage
    at File.normalizeOptions (/Users/kaelan/work/apps/hn-blog-new/node_modules/babel-core/lib/babel/transformation/file.js:91:15)
    at new File (/Users/kaelan/work/apps/hn-blog-new/node_modules/babel-core/lib/babel/transformation/file.js:70:22)
    at Object.transform (/Users/kaelan/work/apps/hn-blog-new/node_modules/babel-core/lib/babel/transformation/index.js:18:14)
    at transpile (/Users/kaelan/work/apps/hn-blog-new/node_modules/babel-loader/index.js:54:24)
    at Object.module.exports (/Users/kaelan/work/apps/hn-blog-new/node_modules/babel-loader/index.js:43:24)
 @ multi app

I'm usign babel-loader like this:

{
    test: /\.jsx?$/,
    loaders: ['react-hot', 'babel-loader?stage=0'],
    exclude: /node_modules/
},

It looks like I'm passing the stage option correctly, removing it solves the error but now generators don't work. Any ideas?

babel loader experimental on webpack

this did not work on webpack test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader?stage=1', how do i enable stage=1 experimental on babel-loader?

ReferenceError: cacheDirectory is not defined

Hi,

currently on window, I have the following trace but can not figure what is wrong

ser.js 831 bytes {0} [built]
  [269] (webpack)-dev-server/~/socket.io-client/~/has-binary/index.js 1.08 kB {0
} [built]
  [270] (webpack)-dev-server/~/socket.io-client/~/has-binary/~/isarray/index.js
120 bytes {0} [built]
  [271] (webpack)-dev-server/~/socket.io-client/~/object-component/index.js 1.18
 kB {0} [built]
  [272] (webpack)-dev-server/~/socket.io-client/~/parseuri/index.js 690 bytes {0
} [built]
  [273] (webpack)-dev-server/~/socket.io-client/~/socket.io-parser/binary.js 3.8
4 kB {0} [built]
  [274] (webpack)-dev-server/~/socket.io-client/~/socket.io-parser/~/json3/lib/j
son3.js 40.1 kB {0} [built]
  [275] (webpack)-dev-server/~/socket.io-client/~/to-array/index.js 216 bytes {0
} [built]
  [276] (webpack)-dev-server/~/strip-ansi/index.js 161 bytes {0} [built]
  [277] (webpack)-dev-server/~/strip-ansi/~/ansi-regex/index.js 145 bytes {0} [b
uilt]
  [278] (webpack)/buildin/amd-options.js 43 bytes {0} [built]
  [279] (webpack)/hot/log-apply-result.js 813 bytes {0} [built]
  [280] ./~/whatwg-fetch/fetch.js 8.54 kB {0} [built]
chunk    {1} app.js (app) 52 bytes {0} [rendered]
    [0] multi app 52 bytes {1} [built] [1 error]

ERROR in ./app/app.js
Module build failed: ReferenceError: cacheDirectory is not defined
    at Object.module.exports (C:/JUL/DEV/github/web-react/node_modules/babel-loa
der/index.js:42:17)
 @ multi app
webpack: bundle is now VALID.`

webpack instruction is the following:

{ test: /\.js?$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/ },`

Passing in options does not seem to work.

I'm attempting to set runtime = true for the use of generators in the 6to5-loader. It looks like this:
{ test: /\.jsx$/, loader: '6to5-loader?runtime=true' }

I get an error Uncaught ReferenceError: regeneratorRuntime is not defined

Is there another way that I'm missing to pass in options?

Source Maps won't work and make webpack crash

Here is a repo to quickly reproduce the error : https://github.com/chollier/babel-webpack-test

Clone it, run npm install then webpack --config webpack.config.js. It will crash.

If in the config I switch babel loader to jsx?harmony :

  module: {
    loaders: [
      { test: /\.jsx.coffee$/, loader: 'jsx?harmony!coffee', exclude: /node_modules/ },
      { test: /\.coffee$/, exclude: /\.jsx.coffee$|node_modules/, loader: 'coffee-loader' },
      { test: /\.js$/, loader: 'jsx?harmony', exclude: /node_modules|rollbar|mixpanel/ },
      { test: /\.json$/, loader: "json" }
    ]
  }

it will work. Which leads me to think it's a babel issue.

Also, if I bring back babel but comment out the source map line and use

    new webpack.optimize.UglifyJsPlugin({sourceMap: false})

it will work as well.

Question about WebPack's async require pattern and 6to5...

Could this example from WebPack's homepage:

function loadTemplateAsync(name, callback) {
    require(["./templates/" + name + ".jade"], 
      function(templateBundle) {
        templateBundle(callback);
    });
}

be written with es6 System.import?

like:

System.import("./some/module")
    .then(module=> doSomething(module))
    .catch(error=>...);

How to output debug information?

I'm using webpack and babel-loader in a gulpfile. In order to get errors in babel-loader reported, I've configured webpack with the options {bail: true, debug: true}. This works fine in that when any of my files contains an error, I get the error reported in the console.

However, I also have a watch task, which automatically runs on changes in any of the files. Problem now is that the watch task exits as soon as an error occurs, which sort of defeats the purpose of watch.

Is there a way to have error output in the console without exiting/crashing the webpack build task?

Experimental flag deprecated, how to set stage flag with Babel 5.0 release

Previously I configured babel-loader in webpack.config.js like this:

            { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?experimental'},

Now that experimental is deprecated, how do I specify the stage param?

I tried

            { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?stage=1'},
            { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?stage 1l'},
            { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?{stage: 1}'},

I also tried adding .babelrc to root of my project with

{
  "stage": 1
}

Can "arguments" be passed into super()?

I'm trying something like

class Foo extends Bar {
  constructor() {
    super(arguments);
  }
}

which doesn't work. But if I manually name the arguments like

class Foo extends Bar {
  constructor(one, two, three) {
    super(one, two, three);
  }
}

then it works!

Is there something regarding super and arguments that I've missed?

Error in output code when using 6to5-loader with coreAliasing

I'm using 6to5-loader with coreAliasing and getting the following error in browser's console:

Uncaught TypeError: Cannot read property 'TypeError' of undefined

It's referencing to TypeError = _core.global.TypeError inside of core-js module. _core object appears to be empty.

Try this project to reproduce error.

Automatic strict mode not working on OSX/Ubuntu

I'm using babel-loader as a loader in my webpack config file as it's explained in the docs (https://babeljs.io/docs/using-babel/#webpack), and I use webpack-dev-server for the automatic reload of the page. This is my whole webpack.config.js:

var webpack = require('webpack');

module.exports = {
    devtool: process.env.NODE_ENV !== 'production' ? 'eval' : null,

    entry: "./app/App.js",

    output: {
        path: '__build__',
        publicPath: '__build__',
        filename: 'build.js'
    },

    module: {
        loaders: [{
            test: /\.js$/,
            exclude: /node_modules\//,
            loader: 'babel-loader'
        }, {
            test: /\.css$/,
            loader: "style!css"
        }, {
            test: /\.(eot|woff2|ttf|svg|woff)$/,
            loader: 'url-loader'
        }]
    },

    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': '"' + process.env.NODE_ENV + '"'
            }
        }),
        new webpack.ProvidePlugin({
            React: "react"
        })
    ]
};

With this configuration, on OSX and Ubuntu I have no problems, but on Windows 8 it breaks, saying that I'm trying to get a WebSocket out of undefined. By inspecting the code, I found out that because of the automatic strict mode, in the browser.js file of the ws package (a dependency of webpack-dev-server, it tries to set this as a variable, which is prevented by the strict mode.
So on Windows I had to blacklist the strict mode, but on OSX/Ubuntu it seems that it's already blacklisted, there's no "use strict"; in my files. Is it a bug or I am missing something?

"Syntax error: Unexpected token <" with webpack-dev-server and HotModuleReplacingPlugin

Cannot make webpack-dev-server successfully reload on the fly my .jsx:

[HMR] Waiting for update signal from WDS...
Actions.js:120 [WDS] Hot Module Replacement enabled.
Actions.js:120 [WDS] App updated. Recompiling...
Actions.js:120 [WDS] App hot update...
Actions.js:120 [HMR] Checking for updates on the server...
Actions.js:120 [HMR] Update failed: SyntaxError: Unexpected token <
    at Object.parse (native)
    at XMLHttpRequest.request.onreadystatechange (http://localhost:9090/build/bundle.js:44:35)

config is as follows:

'use strict';

var webpack = require('webpack');

module.exports = {
    entry: './src/app.js',
    output: {
        path: __dirname + '/public/build/',
        filename: 'bundle.js',
        publicPath: '/build/'
    },
    resolve: {
        extensions: ['', '.js', '.jsx']
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loaders: ['react-hot', 'babel?experimental']
            }
        ]
    },
    plugins: [
        new webpack.NoErrorsPlugin()
    ]
};

using with CLI:

webpack-dev-server --hot --inline --progress --colors --port 9090

Babel-Loader 5.1 breaks downstream loaders

with

loaders: [
    {
        test: /\.js$/,
        loaders: [
            'ng-annotate',
            'babel?' + JSON.stringify({
                cacheDirectory: true,
            }),
            'eslint'
        ]
    }
]
ERROR in ./app/core/app.core.module.js
Module build failed: TypeError: Cannot read property 'length' of undefined
    at new Lut (/var/webclient/node_modules/ng-annotate-loader/node_modules/ng-annotate/build/es5/lut.js:16:37)
    at ngAnnotate (/var/webclient/node_modules/ng-annotate-loader/node_modules/ng-annotate/build/es5/ng-annotate-main.js:1018:15)
    at Object.module.exports (/var/webclient/node_modules/ng-annotate-loader/loader.js:10:13)

Upgrading to babel 5.5.1 breaks configuration

I've been using [email protected] with [email protected] without any issues, but upgrading to babel breaks all my configuration in .babelrc.
Specifically:

  • Previously ignored files are not ignored anymore
  • When running the code it throws an error require is not defined (which I expect is a sign that the runtime is not injected properly?)

Below the configuration

// .babelrc
{
  "stage": 0,
  "optional": [
    "runtime"
  ],
  "ignore": [
    "scripts/vendors/primus.js",
    "scripts/vendors/gunzip.js",
    "node_modules/worker-loader/index.js?inline!*"
  ]
}
// webpack
{
  test: /react\-infinite[\/\\]src[\/\\].*\.js/,
  loader: 'babel-loader'
}, {
  test: /\.js$/,
  exclude: /node_modules/,
  loader: 'babel-loader'
}, {
  test: /worker\.js$/,
  exclude: /node_modules/,
  loader: 'worker?inline!babel-loader'
}

trouble with spread operator

Hi there. Need some help with transpiling a spread operator.
I have code that looks like this:

    var {
      style,
      useContent,
      contentType,
      contentStyle,
      ...other
    } = this.props;

with jsx-loader?harmony, webpack happily transpiles. But with babel-loader, I am getting an error that looks like this:

ERROR in ./app/jsx/components/fullwidth-section.jsx
Module build failed: SyntaxError: /Users/keng/work/virtuosityworks/aubusson/app/jsx/components/fullwidth-section.jsx: Unexpected token (54:6)
52 | contentType,
53 | contentStyle,
`> 54 | ...other
| ^
55 | } = this.props;
56 |

My module config for babel-loader looks like this:

 { test: /\.jsx?$/, loaders: ['babel-loader'], exclude: /node_modules/},

Babel plugins not loaded when using .babelrc

When my plugin is activated through .babelrc the following error is raised:

ReferenceError: The key for plugin "babel-plugin-xxxx" of babel-plugin-xxxx collides with an existing plugin

But when it is activated through loader configuration, everything is fine.

{ test: /\.js$/, include: src, loader: 'babel?' + JSON.stringify({plugins: ['babel-plugin-xxxx']}) },

It seems to be a bug.

Unable to minify transpiled code in babel-loader output

babel-loader generates js file where transpiled code is evaluated using eval function

function(module, exports, __webpack_require__) {
    eval(//* transpiled code *//)
}

Since the code is a string it's not minified and uglified when using babel-loader with UglifyJsPlugin. How can I overcome this limitation ?

Question - how to resolve file paths of modules in node_modules correctly?

Hi,
first of all thanks for the great work bringing 6to5 to webpack!
I am still new to both, please bear with me if it is a simple question.

I want to use 6to5-loader to use ES6 modules with webpack.

When i run webpack with the following configuration:

module: {
        loaders: [
            { test: /\.js$/, exclude: /node_modules/, loader: '6to5-loader?experimental&optional=selfContained'}
        ]
    }

i get the following error:

Module not found: Error: Cannot resolve module '6to5-runtime/helpers' in /to/js/modules/folder

the 6to5-runtime is in the projects local node_modules folder.
How can I adjust the config in a way that the node_modules folder is searched for modules?

i tried addding below lines to the webpack config, without any success:

resolveLoader: {
      root: [
        path.join(__dirname, "node_modules")
      ]
}

A working solution to the issue or some pointers to the right direction are very appreciated.
Thanks in advance!

Second question, is the webpack.ProvidePlugin() still the optimal way to define globals, like jQuery, etc for all modules?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.