Socket
Socket
Sign inDemoInstall

babel-loader

Package Overview
Dependencies
328
Maintainers
4
Versions
77
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 7.0.0-alpha.1 to 7.0.0-alpha.2

34

CHANGELOG.md
# Changelog
## v6.4.0
### 🚀 New Feature
- added metadata passing from babel to webpack, which is currently used by react-intl (#398) @Ognian
## v6.3.2
### 😢 Regression
- `forceEnv` was interfering with regular environment handling
## v6.3.1
### 🐛 Bug Fix
- The new `forceEnv` options wasn't working as expected (#379) @chrisvasz
## v6.3.0
### 🚀 New Feature
- Add new config option `forceEnv` (#368) @moimael
Allow to override BABEL_ENV/NODE_ENV at loader-level. Useful for isomorphic applications which have separate babel config for client and server.
### 🐛 Bug Fix
- Update loader-utils dependency to ^0.2.16 to fix compatibility with webpack 2 (#371) @leonaves
### 💅 Polish
- Improve FS caching to do less sync calls which improves performance slightly (#375) @akx
## v6.2.10

@@ -4,0 +38,0 @@

84

lib/fs-cache.js
"use strict";
/**
* Filesystem cache
*
* Given a file and a transform function, cache the result into files
* or retrieve the previously cached files if the given file is already known.
*
* @see https://github.com/babel/babel-loader/issues/34
* @see https://github.com/babel/babel-loader/pull/41
*/
var crypto = require("crypto");

@@ -11,3 +20,11 @@ var mkdirp = require("mkdirp");

var defaultCacheDirectory = null;
var defaultCacheDirectory = null; // Lazily instantiated when needed
/**
* Read the contents from the compressed file.
*
* @async
* @params {String} filename
* @params {Function} callback
*/
var read = function read(filename, callback) {

@@ -37,2 +54,10 @@ return fs.readFile(filename, function (err, data) {

/**
* Write contents into a compressed file.
*
* @async
* @params {String} filename
* @params {String} result
* @params {Function} callback
*/
var write = function write(filename, result, callback) {

@@ -50,2 +75,10 @@ var content = JSON.stringify(result);

/**
* Build the filename for the cached file
*
* @params {String} source File source code
* @params {Object} options Options used
*
* @return {String}
*/
var filename = function filename(source, identifier, options) {

@@ -64,2 +97,9 @@ var hash = crypto.createHash("SHA1");

/**
* Handle the cache
*
* @params {String} directory
* @params {Object} params
* @params {Function} callback
*/
var handleCache = function handleCache(directory, params, callback) {

@@ -72,3 +112,5 @@ var source = params.source;

// Make sure the directory exists.
mkdirp(directory, function (err) {
// Fallback to tmpdir if node_modules folder not writable
if (err) return shouldFallback ? handleCache(os.tmpdir(), params, callback) : callback(err);

@@ -80,5 +122,8 @@

var result = {};
// No errors mean that the file was previously cached
// we just need to return it
if (!err) return callback(null, content);
// Otherwise just transform the file
// return it to the user asap and write it in cache
try {

@@ -91,2 +136,3 @@ result = transform(source, options);

return write(file, result, function (err) {
// Fallback to tmpdir if node_modules folder not writable
if (err) return shouldFallback ? handleCache(os.tmpdir(), params, callback) : callback(err);

@@ -100,2 +146,36 @@

/**
* Retrieve file from cache, or create a new one for future reads
*
* @async
* @param {Object} params
* @param {String} params.directory Directory to store cached files
* @param {String} params.identifier Unique identifier to bust cache
* @param {String} params.source Original contents of the file to be cached
* @param {Object} params.options Options to be given to the transform fn
* @param {Function} params.transform Function that will transform the
* original file and whose result will be
* cached
*
* @param {Function<err, result>} callback
*
* @example
*
* cache({
* directory: '.tmp/cache',
* identifier: 'babel-loader-cachefile',
* source: *source code from file*,
* options: {
* experimental: true,
* runtime: true
* },
* transform: function(source, options) {
* var content = *do what you need with the source*
* return content;
* }
* }, function(err, result) {
*
* });
*/
module.exports = function (params, callback) {

@@ -102,0 +182,0 @@ var directory = void 0;

104

lib/index.js
"use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var assign = require("object-assign");
var babel = require("babel-core");

@@ -14,4 +11,7 @@ var loaderUtils = require("loader-utils");

var resolveRc = require("./resolve-rc.js");
var pkg = require("./../package.json");
var pkg = require("../package.json");
/**
* Error thrown by Babel formatted to conform to Webpack reporting.
*/
function BabelLoaderError(name, message, codeFrame, hideStack, error) {

@@ -37,2 +37,12 @@ Error.call(this);

var transpile = function transpile(source, options) {
var forceEnv = options.forceEnv;
var tmpEnv = void 0;
delete options.forceEnv;
if (forceEnv) {
tmpEnv = process.env.BABEL_ENV;
process.env.BABEL_ENV = forceEnv;
}
var result = void 0;

@@ -42,2 +52,3 @@ try {

} catch (error) {
if (forceEnv) process.env.BABEL_ENV = tmpEnv;
if (error.message && error.codeFrame) {

@@ -62,2 +73,3 @@ var message = error.message;

var map = result.map;
var metadata = result.metadata;

@@ -68,20 +80,28 @@ if (map && (!map.sourcesContent || !map.sourcesContent.length)) {

if (forceEnv) process.env.BABEL_ENV = tmpEnv;
return {
code: code,
map: map
map: map,
metadata: metadata
};
};
function passMetadata(s, context, metadata) {
if (context[s]) {
context[s](metadata);
}
}
module.exports = function (source, inputSourceMap) {
var _this = this;
var result = {};
// Handle filenames (#106)
var webpackRemainingChain = loaderUtils.getRemainingRequest(this).split("!");
var filename = webpackRemainingChain[webpackRemainingChain.length - 1];
var globalOptions = this.options.babel || {};
var loaderOptions = loaderUtils.parseQuery(this.query);
var userOptions = assign({}, globalOptions, loaderOptions);
// Handle options
var loaderOptions = loaderUtils.getOptions(this);
var defaultOptions = {
metadataSubscribers: [],
inputSourceMap: inputSourceMap,

@@ -93,12 +113,10 @@ sourceRoot: process.cwd(),

"babel-core": babel.version,
babelrc: exists(userOptions.babelrc) ? read(userOptions.babelrc) : resolveRc(path.dirname(filename)),
env: userOptions.forceEnv || process.env.BABEL_ENV || process.env.NODE_ENV
babelrc: exists(loaderOptions.babelrc) ? read(loaderOptions.babelrc) : resolveRc(path.dirname(filename)),
env: loaderOptions.forceEnv || process.env.BABEL_ENV || process.env.NODE_ENV || "development"
})
};
delete userOptions.forceEnv;
var options = Object.assign({}, defaultOptions, loaderOptions);
var options = assign({}, defaultOptions, userOptions);
if (userOptions.sourceMap === undefined) {
if (loaderOptions.sourceMap === undefined) {
options.sourceMap = this.sourceMap;

@@ -113,32 +131,42 @@ }

var cacheIdentifier = options.cacheIdentifier;
var metadataSubscribers = options.metadataSubscribers;
delete options.cacheDirectory;
delete options.cacheIdentifier;
delete options.metadataSubscribers;
this.cacheable();
if (cacheDirectory) {
var _ret = function () {
var callback = _this.async();
return {
v: cache({
directory: cacheDirectory,
identifier: cacheIdentifier,
source: source,
options: options,
transform: transpile
}, function (err, result) {
if (err) {
return callback(err);
}
return callback(null, result.code, result.map);
})
};
}();
var callback = this.async();
return cache({
directory: cacheDirectory,
identifier: cacheIdentifier,
source: source,
options: options,
transform: transpile
}, function (err) {
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
code = _ref.code,
map = _ref.map,
metadata = _ref.metadata;
if ((typeof _ret === "undefined" ? "undefined" : _typeof(_ret)) === "object") return _ret.v;
if (err) return callback(err);
metadataSubscribers.forEach(function (s) {
return passMetadata(s, _this, metadata);
});
return callback(null, code, map);
});
}
result = transpile(source, options);
this.callback(null, result.code, result.map);
var _transpile = transpile(source, options),
code = _transpile.code,
map = _transpile.map,
metadata = _transpile.metadata;
metadataSubscribers.forEach(function (s) {
return passMetadata(s, _this, metadata);
});
this.callback(null, code, map);
};
"use strict";
/**
* The purpose of this module, is to find the project's .babelrc and
* use its contents to bust the babel-loader's internal cache whenever an option
* changes.
*
* @see https://github.com/babel/babel-loader/issues/62
* @see http://git.io/vLEvu
*/
var path = require("path");

@@ -18,2 +26,3 @@ var exists = require("./utils/exists")({});

if (up !== start) {
// Reached root
return find(up, rel);

@@ -20,0 +29,0 @@ }

"use strict";
var fs = require("fs");
/**
* Check if file exists and cache the result
* return the result in cache
*
* @example
* var exists = require('./helpers/fsExists')({});
* exists('.babelrc'); // false
*/
module.exports = function (cache) {

@@ -6,0 +13,0 @@ cache = cache || {};

"use strict";
var fs = require("fs");
/**
* Read the file and cache the result
* return the result in cache
*
* @example
* var read = require('./helpers/fsExists')({});
* read('.babelrc'); // file contents...
*/
module.exports = function (cache) {

@@ -6,0 +13,0 @@ cache = cache || {};

@@ -9,2 +9,3 @@ "use strict";

// If the file is in a completely different root folder use the absolute path of file.
if (rootPath && rootPath !== fileRootPath) {

@@ -11,0 +12,0 @@ return filename;

{
"name": "babel-loader",
"version": "7.0.0-alpha.1",
"version": "7.0.0-alpha.2",
"description": "babel module loader for webpack",

@@ -9,11 +9,13 @@ "files": [

"main": "lib/index.js",
"engines": {
"node": ">=4"
},
"dependencies": {
"find-cache-dir": "^0.1.1",
"loader-utils": "^0.2.16",
"mkdirp": "^0.5.1",
"object-assign": "^4.0.1"
"loader-utils": "^1.0.2",
"mkdirp": "^0.5.1"
},
"peerDependencies": {
"babel-core": "6 || 7 || ^7.0.0-alpha || ^7.0.0-beta || ^7.0.0-rc",
"webpack": "1 || 2 || ^2.1.0-beta || ^2.2.0-rc"
"webpack": "2"
},

@@ -26,4 +28,4 @@ "devDependencies": {

"babel-plugin-istanbul": "^4.0.0",
"babel-preset-es2015": "^6.0.0",
"babel-preset-latest": "^6.16.0",
"babel-plugin-react-intl": "^2.1.3",
"babel-preset-env": "^1.2.0",
"babel-register": "^6.18.0",

@@ -36,4 +38,7 @@ "codecov": "^1.0.1",

"nyc": "^10.0.0",
"react": "^15.1.0",
"react-intl": "^2.1.2",
"react-intl-webpack-plugin": "^0.0.3",
"rimraf": "^2.4.3",
"webpack": "^2.2.0-rc"
"webpack": "^2.2.0"
},

@@ -45,6 +50,6 @@ "scripts": {

"lint": "eslint src test",
"preversion": "yarn test",
"prepublish": "yarn clean && yarn build",
"test": "yarn lint && cross-env BABEL_ENV=test yarn build && yarn test-only",
"test-ci": "cross-env BABEL_ENV=test yarn build && yarn test-only",
"preversion": "yarn run test",
"prepublish": "yarn run clean && yarn run build",
"test": "yarn run lint && cross-env BABEL_ENV=test yarn run build && yarn run test-only",
"test-ci": "cross-env BABEL_ENV=test yarn run build && yarn run test-only",
"test-only": "nyc ava"

@@ -51,0 +56,0 @@ },

@@ -1,2 +0,1 @@

# babel-loader
[![NPM Status](https://img.shields.io/npm/v/babel-loader.svg?style=flat)](https://www.npmjs.com/package/babel-loader)

@@ -6,39 +5,46 @@ [![Build Status](https://travis-ci.org/babel/babel-loader.svg?branch=master)](https://travis-ci.org/babel/babel-loader)

[![codecov](https://codecov.io/gh/babel/babel-loader/branch/master/graph/badge.svg)](https://codecov.io/gh/babel/babel-loader)
> Babel is a compiler for writing next generation JavaScript.
This package allows transpiling JavaScript files using [Babel](https://github.com/babel/babel) and [webpack](https://github.com/webpack/webpack).
<div align="center">
<a href="https://github.com/babel/babel/">
<img width="200" height="200" src="https://rawgit.com/babel/logo/master/babel.svg">
</a>
<a href="https://github.com/webpack/webpack">
<img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg">
</a>
<h1>Babel Loader</h1>
</div>
__Notes:__ Issues with the output should be reported on the babel [issue tracker](https://github.com/babel/babel/issues);
This package allows transpiling JavaScript files using [Babel](https://github.com/babel/babel) and [webpack](https://github.com/webpack/webpack).
## Installation
__Notes:__ Issues with the output should be reported on the babel [issue tracker](https://github.com/babel/babel/issues);
<h2 align="center">Install</h2>
```bash
npm install babel-loader babel-core babel-preset-es2015 webpack --save-dev
yarn add babel-loader babel-core babel-preset-env webpack --dev
```
or
We recommend using yarn, but you can also still use npm:
```bash
yarn add babel-loader babel-core babel-preset-es2015 webpack --dev
npm install --save-dev babel-loader babel-core babel-preset-env webpack
```
__Note:__ [npm](https://npmjs.com) deprecated [auto-installing of peerDependencies](https://github.com/npm/npm/issues/6565) since npm@3, so required peer dependencies like babel-core and webpack must be listed explicitly in your `package.json`.
<h2 align="center">Usage</h2>
__Note:__ If you're upgrading from babel 5 to babel 6, please take a look [at this guide](https://medium.com/@malyw/how-to-update-babel-5-x-6-x-d828c230ec53#.yqxukuzdk).
[Documentation: Using loaders](https://webpack.js.org/loaders/)
## Usage
Within your webpack configuration object, you'll need to add the babel-loader to the list of modules, like so:
[Documentation: Using loaders](http://webpack.github.io/docs/using-loaders.html)
Within your webpack configuration object, you'll need to add the babel-loader to the list of modules, like so:
```javascript
```javascript
module: {
loaders: [
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['es2015']
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}

@@ -48,33 +54,22 @@ }

}
```
```
### Options
See the `babel` [options](http://babeljs.io/docs/usage/options/).
See the `babel` [options](https://babeljs.io/docs/usage/api/#options).
You can pass options to the loader by writing them as a [query string](https://github.com/webpack/loader-utils):
You can pass options to the loader by using the [options property](https://webpack.js.org/configuration/module/#rule-options-rule-query):
```javascript
```javascript
module: {
loaders: [
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader?presets[]=es2015'
}
]
}
```
or by using the [query property](https://webpack.github.io/docs/using-loaders.html#query-parameters):
```javascript
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['es2015']
use: {
loader: 'babel-loader',
options: {
presets: ['env'],
plugins: [require('babel-plugin-transform-object-rest-spread')]
}
}

@@ -84,16 +79,14 @@ }

}
```
```
This loader also supports the following loader-specific option:
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 blank (`loader: 'babel-loader?cacheDirectory'`) or `true` (`loader: babel-loader?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.
* `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 blank (`loader: 'babel-loader?cacheDirectory'`) or `true` (`loader: babel-loader?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.
* `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.
* `babelrc`: Default `true`. When `false`, will ignore `.babelrc` files (except those referenced by the `extends` option).
* `forceEnv`: Default will resolve BABEL_ENV then NODE_ENV. Allow you to override BABEL_ENV/NODE_ENV at the loader level. Useful for isomorphic applications with different babel configuration for client and server.
* `forceEnv`: Default will resolve BABEL_ENV then NODE_ENV. Allow you to override BABEL_ENV/NODE_ENV at the loader level. Useful for isomorphic applications with different babel configuration for client and server.
__Note:__ The `sourceMap` option is ignored, instead sourceMaps are automatically enabled when webpack is configured to use them (via the `devtool` config option).
__Note:__ The `sourceMap` option is ignored, instead sourceMaps are automatically enabled when webpack is configured to use them (via the `devtool` config option).
## Troubleshooting

@@ -103,27 +96,27 @@

Make sure you are transforming as few files as possible. Because you are probably
matching `/\.js$/`, you might be transforming the `node_modules` folder or other unwanted
source.
Make sure you are transforming as few files as possible. Because you are probably
matching `/\.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.
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.
You can also speed up babel-loader by as much as 2x by using the `cacheDirectory` option.
This will cache transformations to the filesystem.
### 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.
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.
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, instead
requiring `babel-plugin-transform-runtime` and making all helper references use it.
The following configuration disables automatic per-file runtime injection in babel, instead
requiring `babel-plugin-transform-runtime` and making all helper references use it.
See the [docs](http://babeljs.io/docs/plugins/transform-runtime/) for more information.
See the [docs](http://babeljs.io/docs/plugins/transform-runtime/) for more information.
**NOTE:** You must run `npm install babel-plugin-transform-runtime --save-dev` to include this in your project and `babel-runtime` itself as a dependency with `npm install babel-runtime --save`.
**NOTE:** You must run `npm install babel-plugin-transform-runtime --save-dev` to include this in your project and `babel-runtime` itself as a dependency with `npm install babel-runtime --save`.
```javascript
loaders: [
rules: [
// the 'transform-runtime' plugin tells babel to require the runtime

@@ -134,6 +127,8 @@ // instead of inlining it.

exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['es2015'],
plugins: ['transform-runtime']
use: {
loader: 'babel-loader',
options: {
presets: ['env'],
plugins: ['transform-runtime']
}
}

@@ -140,0 +135,0 @@ }

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc