Пример #1
0
Файл: api.js Проект: Chan-PH/ava
	_setupPrecompiler(files) {
		const isCacheEnabled = this.options.cacheEnabled !== false;
		let cacheDir = uniqueTempDir();

		if (isCacheEnabled) {
			const foundDir = findCacheDir({
				name: 'ava',
				files
			});
			if (foundDir !== null) {
				cacheDir = foundDir;
			}
		}

		this.options.cacheDir = cacheDir;

		const isPowerAssertEnabled = this.options.powerAssert !== false;
		return babelConfigHelper.build(this.options.projectDir, cacheDir, this.options.babelConfig, isPowerAssertEnabled)
			.then(result => {
				this.precompiler = new CachingPrecompiler({
					path: cacheDir,
					getBabelOptions: result.getOptions,
					babelCacheKeys: result.cacheKeys
				});
			});
	}
Пример #2
0
Файл: api.js Проект: a780201/ava
		.then(function (files) {
			if (files.length === 0) {
				self._handleExceptions({
					exception: new AvaError('Couldn\'t find any files to test'),
					file: undefined
				});

				return [];
			}

			var cacheEnabled = self.options.cacheEnabled !== false;
			var cacheDir = (cacheEnabled && findCacheDir({name: 'ava', files: files})) ||
				uniqueTempDir();

			self.options.cacheDir = cacheDir;
			self.precompiler = new CachingPrecompiler(cacheDir);
			self.fileCount = files.length;
			self.base = path.relative('.', commonPathPrefix(files)) + path.sep;

			var tests = files.map(self._runFile);

			// receive test count from all files and then run the tests
			var statsCount = 0;

			return new Promise(function (resolve) {
				tests.forEach(function (test) {
					function tryRun() {
						if (++statsCount === self.fileCount) {
							self.emit('ready');

							var method = self.options.serial ? 'mapSeries' : 'map';
							var options = {
								runOnlyExclusive: self.hasExclusive
							};

							resolve(Promise[method](files, function (file, index) {
								return tests[index].run(options).catch(function (err) {
									// The test failed catastrophically. Flag it up as an
									// exception, then return an empty result. Other tests may
									// continue to run.
									self._handleExceptions({
										exception: err,
										file: file
									});

									return {
										stats: {passCount: 0, skipCount: 0, todoCount: 0, failCount: 0},
										tests: []
									};
								});
							}));
						}
					}

					test.on('stats', tryRun);
					test.catch(tryRun);
				});
			});
		})
Пример #3
0
module.exports = function(params, callback) {
  let directory;

  if (typeof params.directory === "string") {
    directory = params.directory;
  } else {
    directory = findCacheDir({ name: "babel-loader" }) || os.tmpdir();
  }

  handleCache(directory, params, callback);
};
Пример #4
0
function NYC (config) {
  config = config || {}
  this.config = config

  this.subprocessBin = config.subprocessBin || path.resolve(__dirname, './bin/nyc.js')
  this._tempDirectory = config.tempDir || config.tempDirectory || './.nyc_output'
  this._instrumenterLib = require(config.instrumenter || './lib/instrumenters/istanbul')
  this._reportDir = config.reportDir || 'coverage'
  this._sourceMap = typeof config.sourceMap === 'boolean' ? config.sourceMap : true
  this._showProcessTree = config.showProcessTree || false
  this._eagerInstantiation = config.eager || false
  this.cwd = config.cwd || process.cwd()
  this.reporter = arrify(config.reporter || 'text')

  this.cacheDirectory = (config.cacheDir && path.resolve(config.cacheDir)) || findCacheDir({name: 'nyc', cwd: this.cwd})
  this.cache = Boolean(this.cacheDirectory && config.cache)

  this.exclude = testExclude({
    cwd: this.cwd,
    include: config.include,
    exclude: config.exclude
  })

  this.sourceMaps = new SourceMaps({
    cache: this.cache,
    cacheDirectory: this.cacheDirectory
  })

  // require extensions can be provided as config in package.json.
  this.require = arrify(config.require)

  this.extensions = arrify(config.extension).concat('.js').map(function (ext) {
    return ext.toLowerCase()
  }).filter(function (item, pos, arr) {
    // avoid duplicate extensions
    return arr.indexOf(item) === pos
  })

  this.transforms = this.extensions.reduce(function (transforms, ext) {
    transforms[ext] = this._createTransform(ext)
    return transforms
  }.bind(this), {})

  this.hookRequire = config.hookRequire
  this.hookRunInContext = config.hookRunInContext
  this.hookRunInThisContext = config.hookRunInThisContext
  this.fakeRequire = null

  this.processInfo = new ProcessInfo(config && config._processInfo)
  this.rootId = this.processInfo.root || this.generateUniqueID()

  this.hashCache = {}
}
Пример #5
0
Файл: api.js Проект: Ollynov/ava
Api.prototype._run = function (files, _options) {
	var self = this;
	var runStatus = new RunStatus({
		prefixTitles: this.options.explicitTitles || files.length > 1,
		runOnlyExclusive: _options && _options.runOnlyExclusive,
		base: path.relative('.', commonPathPrefix(files)) + path.sep
	});

	if (self.options.timeout) {
		var timeout = ms(self.options.timeout);
		runStatus._restartTimer = debounce(function () {
			self._onTimeout(runStatus);
		}, timeout);
		runStatus._restartTimer();
		runStatus.on('test', runStatus._restartTimer);
	}

	self.emit('test-run', runStatus, files);

	if (files.length === 0) {
		runStatus.handleExceptions({
			exception: new AvaError('Couldn\'t find any files to test'),
			file: undefined
		});

		return Promise.resolve(runStatus);
	}

	var cacheEnabled = self.options.cacheEnabled !== false;
	var cacheDir = (cacheEnabled && findCacheDir({
		name: 'ava',
		files: files
	})) || uniqueTempDir();

	self.options.cacheDir = cacheDir;
	self.precompiler = new CachingPrecompiler(cacheDir, self.options.babelConfig);
	self.fileCount = files.length;

	var overwatch;
	if (this.options.concurrency > 0) {
		overwatch = this._runLimitedPool(files, runStatus, self.options.serial ? 1 : this.options.concurrency);
	} else {
		// _runNoPool exists to preserve legacy behavior, specifically around `.only`
		overwatch = this._runNoPool(files, runStatus);
	}

	return overwatch;
};
Пример #6
0
function NYC (opts) {
  var config = this._loadConfig(opts || {})

  this._istanbul = config.istanbul
  this.subprocessBin = config.subprocessBin || path.resolve(__dirname, './bin/nyc.js')
  this._tempDirectory = config.tempDirectory || './.nyc_output'
  this._reportDir = config.reportDir
  this.cwd = config.cwd

  this.reporter = arrify(config.reporter || 'text')

  // load exclude stanza from config.
  this.include = false
  if (config.include && config.include.length > 0) {
    this.include = this._prepGlobPatterns(arrify(config.include))
  }

  this.exclude = this._prepGlobPatterns(
    ['**/node_modules/**'].concat(arrify(
      config.exclude && config.exclude.length > 0
        ? config.exclude
        : ['test/**', 'test{,-*}.js', '**/*.test.js', '**/__tests__/**']
      ))
  )

  this.cacheDirectory = findCacheDir({name: 'nyc', cwd: this.cwd})

  this.enableCache = Boolean(this.cacheDirectory && (config.enableCache === true || process.env.NYC_CACHE === 'enable'))

  // require extensions can be provided as config in package.json.
  this.require = arrify(config.require)

  this.extensions = arrify(config.extension).concat('.js').map(function (ext) {
    return ext.toLowerCase()
  })

  this.transforms = this.extensions.reduce(function (transforms, ext) {
    transforms[ext] = this._createTransform(ext)
    return transforms
  }.bind(this), {})

  this.sourceMapCache = new SourceMapCache()

  this.hashCache = {}
  this.loadedMaps = null
}
Пример #7
0
  var _ref4 = _asyncToGenerator(function* (params) {
    let directory;

    if (typeof params.cacheDirectory === "string") {
      directory = params.cacheDirectory;
    } else {
      if (defaultCacheDirectory === null) {
        defaultCacheDirectory = findCacheDir({
          name: "babel-loader"
        }) || os.tmpdir();
      }

      directory = defaultCacheDirectory;
    }

    return yield handleCache(directory, params);
  });
Пример #8
0
function NYC (opts) {
  var config = this._loadConfig(opts || {})

  this._istanbul = config.istanbul
  this.subprocessBin = config.subprocessBin || path.resolve(__dirname, './bin/nyc.js')
  this._tempDirectory = config.tempDirectory || './.nyc_output'
  this._instrumenterLib = require(config.instrumenter || './lib/instrumenters/istanbul')
  this._reportDir = config.reportDir
  this._sourceMap = config.sourceMap
  this.cwd = config.cwd

  this.reporter = arrify(config.reporter || 'text')

  this.cacheDirectory = findCacheDir({name: 'nyc', cwd: this.cwd})

  this.enableCache = Boolean(this.cacheDirectory && (config.enableCache === true || process.env.NYC_CACHE === 'enable'))

  this.exclude = testExclude({
    cwd: this.cwd,
    include: config.include,
    exclude: config.exclude
  })

  // require extensions can be provided as config in package.json.
  this.require = arrify(config.require)

  this.extensions = arrify(config.extension).concat('.js').map(function (ext) {
    return ext.toLowerCase()
  }).filter(function (item, pos, arr) {
    // avoid duplicate extensions
    return arr.indexOf(item) === pos
  })

  this.transforms = this.extensions.reduce(function (transforms, ext) {
    transforms[ext] = this._createTransform(ext)
    return transforms
  }.bind(this), {})

  this.sourceMapCache = libSourceMaps.createSourceMapStore()

  this.hookRunInContext = config.hookRunInContext
  this.hashCache = {}
  this.loadedMaps = null
  this.fakeRequire = null
}
Пример #9
0
// `baseConfig` is a webpack configuration bundled with storybook.
// Storybook will look in the `configDir` directory
// (inside working directory) if a config path is not provided.
export default options => {
  const {
    configType,
    getBaseConfig,
    configDir,
    defaultConfigName,
    wrapInitialConfig = noopWrapper,
    wrapBasicConfig = noopWrapper,
    wrapDefaultConfig = noopWrapper,
  } = options;

  const babelOptions = {
    // This is a feature of `babel-loader` for webpack (not Babel itself).
    // It enables a cache directory for faster-rebuilds
    // `find-cache-dir` will create the cache directory under the node_modules directory.
    cacheDirectory: findCacheDir({ name: 'react-storybook' }),
    ...getBabelConfig(options),
  };
  const baseConfig = getBaseConfig({ ...options, babelOptions });
  const config = wrapInitialConfig(baseConfig, configDir);

  const defaultConfig = wrapDefaultConfig(createDefaultWebpackConfig(config));

  // Check whether user has a custom webpack config file and
  // return the (extended) base configuration if it's not available.
  const customConfigPath = path.resolve(configDir, 'webpack.config.js');

  if (!fs.existsSync(customConfigPath)) {
    informAboutCustomConfig(defaultConfigName);
    return defaultConfig;
  }

  const customConfig = require(customConfigPath);

  if (typeof customConfig === 'function') {
    logger.info('=> Loading custom webpack config (full-control mode).');
    return customConfig(wrapBasicConfig(config), configType, defaultConfig);
  }

  logger.info('=> Loading custom webpack config (extending mode).');

  return mergeConfigs(config, customConfig);
};
module.exports = function(input, map) {
  var config = assign(
    // loader defaults
    {
      formatter: require("eslint/lib/formatters/stylish"),
    },
    // user defaults
    this.options.eslint || {},
    // loader query string
    loaderUtils.parseQuery(this.query)
  )
  this.cacheable()

  // Create the engine only once per config
  var configHash = objectHash(config)
  if (!engines[configHash]) {
    engines[configHash] = new eslint.CLIEngine(config)
  }

  // Read the cached information only once and if enable
  if (cache === null) {
    if (config.cache) {
      var thunk = findCacheDir({
        name: "eslint-loader",
        thunk: true,
        create: true,
      })
      cachePath = thunk("data.json")
      try {
        cache = require(cachePath)
      }
      catch (e) {
        cache = {}
      }
    }
    else {
      cache = false
    }
  }

  lint(input, config, this)
  this.callback(null, input, map)
}
Пример #11
0
var cache = module.exports = function(params, callback) {
  // Spread params into named variables
  // Forgive user whenever possible
  var source = params.source;
  var options = params.options || {};
  var transform = params.transform;
  var identifier = params.identifier;
  var directory;

  if (typeof params.directory === 'string') {
    directory = params.directory;
  } else {
    directory = findCacheDir({ name: 'babel-loader' }) || os.tmpdir();
  }

  var file = path.join(directory, filename(source, identifier, options));

  // Make sure the directory exists.
  return mkdirp(directory, function(err) {
    if (err) { return callback(err); }

    return read(file, function(err, content) {
      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 {
        result = transform(source, options);
      } catch (error) {
        return callback(error);
      }

      return write(file, result, function(err) {
        return callback(err, result);
      });
    });
  });
};
Пример #12
0
function NYC (opts) {
  opts = opts || {}

  this._istanbul = opts.istanbul
  this.subprocessBin = opts.subprocessBin || path.resolve(__dirname, './bin/nyc.js')
  this._tempDirectory = opts.tempDirectory || './.nyc_output'

  var config = this._loadConfig(opts)
  this.cwd = config.cwd

  this.reporter = arrify(opts.reporter || 'text')

  // load exclude stanza from config.
  this.include = false
  if (config.include) {
    this.include = this._prepGlobPatterns(arrify(config.include))
  }

  this.exclude = this._prepGlobPatterns(
    ['**/node_modules/**'].concat(arrify(config.exclude || ['test/**', 'test{,-*}.js']))
  )

  this.cacheDirectory = findCacheDir({name: 'nyc', cwd: this.cwd})

  this.enableCache = Boolean(this.cacheDirectory && (opts.enableCache === true || process.env.NYC_CACHE === 'enable'))

  // require extensions can be provided as config in package.json.
  this.require = arrify(config.require || opts.require)

  this.transform = this._createTransform()

  this.sourceMapCache = new SourceMapCache()

  this.hashCache = {}
  this.loadedMaps = null
}
Пример #13
0
module.exports = function (cacheName, cwd) {
	var cacheDir = findCacheDir({name: cacheName, cwd: cwd});
	return express.static(cacheDir);
};
Пример #14
0
		.then(function (files) {
			if (files.length === 0) {
				self._handleExceptions({
					exception: new AvaError('Couldn\'t find any files to test'),
					file: undefined
				});

				return [];
			}

			var cacheEnabled = self.options.cacheEnabled !== false;
			var cacheDir = (cacheEnabled && findCacheDir({name: 'ava', files: files})) ||
				uniqueTempDir();

			self.options.cacheDir = cacheDir;
			self.precompiler = new CachingPrecompiler(cacheDir, self.options.babelConfig);
			self.fileCount = files.length;
			self.base = path.relative('.', commonPathPrefix(files)) + path.sep;

			var tests = new Array(self.fileCount);
			return new Promise(function (resolve) {
				function run() {
					if (self.options.match.length > 0 && !self.hasExclusive) {
						self._handleExceptions({
							exception: new AvaError('Couldn\'t find any matching tests'),
							file: undefined
						});

						resolve([]);
						return;
					}

					self.emit('ready');

					var method = self.options.serial ? 'mapSeries' : 'map';
					var options = {
						runOnlyExclusive: self.hasExclusive
					};

					resolve(Promise[method](files, function (file, index) {
						return tests[index].run(options).catch(function (err) {
							// The test failed catastrophically. Flag it up as an
							// exception, then return an empty result. Other tests may
							// continue to run.
							self._handleExceptions({
								exception: err,
								file: file
							});

							return {
								stats: {passCount: 0, skipCount: 0, todoCount: 0, failCount: 0},
								tests: []
							};
						});
					}));
				}

				// receive test count from all files and then run the tests
				var unreportedFiles = self.fileCount;
				var bailed = false;
				files.every(function (file, index) {
					var tried = false;
					function tryRun() {
						if (!tried && !bailed) {
							tried = true;
							unreportedFiles--;
							if (unreportedFiles === 0) {
								run();
							}
						}
					}

					try {
						var test = tests[index] = self._runFile(file);
						test.on('stats', tryRun);
						test.catch(tryRun);
						return true;
					} catch (err) {
						bailed = true;
						self._handleExceptions({
							exception: err,
							file: file
						});
						resolve([]);
						return false;
					}
				});
			}).then(function (results) {
				if (results.length === 0) {
					// No tests ran, make sure to tear down the child processes.
					tests.forEach(function (test) {
						test.send('teardown');
					});
				}

				return results;
			});
		})
Пример #15
0
Api.prototype._run = function (files, _options) {
	var self = this;
	var runStatus = new TestData({
		prefixTitles: this.options.explicitTitles || files.length > 1,
		runOnlyExclusive: _options && _options.runOnlyExclusive,
		base: path.relative('.', commonPathPrefix(files)) + path.sep
	});

	if (self.options.timeout) {
		var timeout = ms(self.options.timeout);
		runStatus._restartTimer = debounce(function () {
			self._onTimeout(runStatus);
		}, timeout);
		runStatus._restartTimer();
		runStatus.on('test', runStatus._restartTimer);
	}

	self.emit('test-run', runStatus, files);

	if (files.length === 0) {
		runStatus.handleExceptions({
			exception: new AvaError('Couldn\'t find any files to test'),
			file: undefined
		});

		return Promise.resolve([]);
	}

	var cacheEnabled = self.options.cacheEnabled !== false;
	var cacheDir = (cacheEnabled && findCacheDir({name: 'ava', files: files})) ||
		uniqueTempDir();

	self.options.cacheDir = cacheDir;
	self.precompiler = new CachingPrecompiler(cacheDir, self.options.babelConfig);
	self.fileCount = files.length;

	var tests = new Array(self.fileCount);

	// TODO: thid should be cleared at the end of the run
	runStatus.on('timeout', function () {
		tests.forEach(function (fork) {
			fork.exit();
		});
	});

	return new Promise(function (resolve) {
		function run() {
			if (self.options.match.length > 0 && !runStatus.hasExclusive) {
				runStatus.handleExceptions({
					exception: new AvaError('Couldn\'t find any matching tests'),
					file: undefined
				});

				resolve([]);
				return;
			}

			self.emit('ready');

			var method = self.options.serial ? 'mapSeries' : 'map';
			var options = {
				runOnlyExclusive: runStatus.hasExclusive
			};

			resolve(Promise[method](files, function (file, index) {
				return tests[index].run(options).catch(function (err) {
					// The test failed catastrophically. Flag it up as an
					// exception, then return an empty result. Other tests may
					// continue to run.
					runStatus.handleExceptions({
						exception: err,
						file: file
					});

					return {
						stats: {
							passCount: 0,
							skipCount: 0,
							todoCount: 0,
							failCount: 0
						},
						tests: []
					};
				});
			}));
		}

		// receive test count from all files and then run the tests
		var unreportedFiles = self.fileCount;
		var bailed = false;

		files.every(function (file, index) {
			var tried = false;

			function tryRun() {
				if (!tried && !bailed) {
					tried = true;
					unreportedFiles--;

					if (unreportedFiles === 0) {
						run();
					}
				}
			}

			try {
				var test = tests[index] = self._runFile(file, runStatus);

				test.on('stats', tryRun);
				test.catch(tryRun);

				return true;
			} catch (err) {
				bailed = true;

				runStatus.handleExceptions({
					exception: err,
					file: file
				});

				resolve([]);

				return false;
			}
		});
	}).then(function (results) {
		if (results.length === 0) {
			// No tests ran, make sure to tear down the child processes.
			tests.forEach(function (test) {
				test.send('teardown');
			});
		}

		return results;
	}).then(function (results) {
		// cancel debounced _onTimeout() from firing
		if (self.options.timeout) {
			runStatus._restartTimer.cancel();
		}

		runStatus.processResults(results);
		return runStatus;
	});
};
Пример #16
0
		'serial',
		'tap'
	],
	default: conf,
	alias: {
		r: 'require',
		s: 'serial'
	}
});

if (cli.input.length !== 1) {
	throw new Error('Specify a test file');
}

var file = path.resolve(cli.input[0]);
var cacheDir = findCacheDir({name: 'ava', files: [file]}) || uniqueTempDir();
var opts = {
	file: file,
	failFast: cli.flags.failFast,
	serial: cli.flags.serial,
	require: arrify(cli.flags.require),
	tty: false,
	cacheDir: cacheDir,
	precompiled: new CachingPrecompiler(cacheDir, conf.babel).generateHashForFile(file)
};

var events = new EventEmitter();

// Mock the behavior of a parent process.
process.send = function (data) {
	if (data && data.ava) {
Пример #17
0
import findCacheDir from "find-cache-dir";
import levelUp from "levelup";
import levelDown from "leveldown";
import subLevel from "level-sublevel";

const cacheDir = findCacheDir({ name: "phenomic/db", create: true });

const database = levelUp(cacheDir);
const level = subLevel(database);
const options = { valueEncoding: "json" };
const wrapStreamConfig = config => Object.assign({}, config, options);

function getSublevel(
  db: Sublevel,
  sub: string | Array<string>,
  filter: ?string,
  filterValue: ?string
) {
  if (!Array.isArray(sub)) {
    sub = [sub];
  }
  if (filter) {
    sub = sub.concat(filter);
    if (filter !== "default" && filterValue) {
      sub = sub.concat(filterValue);
    }
  }
  return sub.reduce((db: Sublevel, name) => db.sublevel(name), db);
}

async function getDataRelation(fieldName, keys) {
Пример #18
0
// @flow
import { join, basename } from "path"
import { BannerPlugin } from "webpack"
import findCacheDir from "find-cache-dir"

import commonWebpackConfig from "./config.common.js"

const chunkNameNode = "phenomic.node"
const cacheDir = findCacheDir({ name: "phenomic" })

export default (config: Object): Object => {
  const webpackConfig = commonWebpackConfig(config)
  return {
    ...webpackConfig,

    entry: {
      // no need for other entries
      [chunkNameNode]: join(config.cwd, config.scriptNode),
    },

    output: {
      ...webpackConfig.output,
      path: cacheDir,
      libraryTarget: "commonjs2",
      filename: basename(config.scriptNode, ".js") + ".bundle.js",
    },

    target: "node",

    // externals for package/relative name
    externals: [
import webpack from 'webpack';
import Dotenv from 'dotenv-webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import CaseSensitivePathsPlugin from 'case-sensitive-paths-webpack-plugin';
import uiPaths from '@storybook/ui/paths';

import findCacheDir from 'find-cache-dir';

import { version } from '../../../package.json';
import { getManagerHeadHtml } from '../utils/template';
import { loadEnv } from '../config/utils';
import babelLoader from '../common/babel-loader';

const coreDirName = path.dirname(require.resolve('@storybook/core/package.json'));
const context = path.join(coreDirName, '../../node_modules');
const cacheDir = findCacheDir({ name: 'storybook' });

export default ({ configDir, configType, entries, dll, outputDir, cache, babelOptions }) => {
  const { raw, stringified } = loadEnv();
  const isProd = configType === 'PRODUCTION';

  return {
    name: 'manager',
    mode: isProd ? 'production' : 'development',
    bail: isProd,
    devtool: 'none',
    entry: entries,
    output: {
      path: outputDir,
      filename: '[name].[chunkhash].bundle.js',
      publicPath: '',
Пример #20
0
 },
 module: {
   preLoaders: [
     {
       test: /\.js$/,
       loader: 'eslint',
       include: paths.project(config.get('dir_src')),
     },
   ],
   loaders: [
     {
       test: /\.js$/,
       include: paths.project(config.get('dir_src')),
       loader: 'babel',
       query: {
         cacheDirectory: ifProd(false, findCacheDir({ name: 'client-bundle' })),
         presets: ['latest', 'react'],
         plugins: [
           'syntax-async-functions',
           'syntax-export-extensions',
           'transform-class-properties',
           'transform-export-extensions',
           'transform-regenerator',
           'transform-object-rest-spread',
           'syntax-trailing-function-commas',
         ],
         env: {
           development: {
             plugins: [
               'transform-react-jsx-source',
               'transform-react-jsx-self',
Пример #21
0
// `baseConfig` is a webpack configuration bundled with storybook.
// Storybook will look in the `configDir` directory
// (inside working directory) if a config path is not provided.
export default function(configType, baseConfig, projectDir, configDir) {
  const config = baseConfig;

  // Search for a .babelrc in project directory, config directory, and storybook
  // module directory. If found, use that to extend webpack configurations.
  const babelConfigInConfig = loadBabelConfig(path.resolve(configDir, '.babelrc'));
  const babelConfigInProject = loadBabelConfig(path.resolve(projectDir, '.babelrc'));
  const babelConfigInModule = loadBabelConfig('.babelrc');

  let babelConfig = null;
  let babelConfigDir = '';

  if (babelConfigInConfig) {
    logger.info('=> Loading custom .babelrc from config directory.');
    babelConfig = babelConfigInConfig;
    babelConfigDir = configDir;
  } else if (babelConfigInProject) {
    logger.info('=> Loading custom .babelrc from project directory.');
    babelConfig = babelConfigInProject;
    babelConfigDir = projectDir;
  } else {
    babelConfig = babelConfigInModule;
  }

  if (babelConfig) {
    // If the custom config uses babel's `extends` clause, then replace it with
    // an absolute path. `extends` will not work unless we do this.
    if (babelConfig.extends) {
      babelConfig.extends = babelConfigDir
        ? path.resolve(babelConfigDir, babelConfig.extends)
        : path.resolve(babelConfig.extends);
    }
    config.module.rules[0].query = babelConfig;
  }

  // This is a feature of `babel-loader` for webpack (not Babel itself).
  // It enables a cache directory for faster-rebuilds
  // `find-cache-dir` will create the cache directory under the node_modules directory.
  config.module.rules[0].query.cacheDirectory = findCacheDir({
    name: 'react-storybook',
  });

  // Check whether addons.js file exists inside the storybook.
  // Load the default addons.js file if it's missing.
  const storybookDefaultAddonsPath = path.resolve(__dirname, 'addons.js');
  const storybookCustomAddonsPath = path.resolve(configDir, 'addons.js');
  if (fs.existsSync(storybookCustomAddonsPath)) {
    logger.info('=> Loading custom addons config.');
    config.entry.manager.unshift(storybookCustomAddonsPath);
  } else {
    config.entry.manager.unshift(storybookDefaultAddonsPath);
  }

  const defaultConfig = createDefaultWebpackConfig(config);

  // Check whether user has a custom webpack config file and
  // return the (extended) base configuration if it's not available.
  const customConfigPath = path.resolve(configDir, 'webpack.config.js');
  if (!fs.existsSync(customConfigPath)) {
    logger.info('=> Using default webpack setup based on "Create React App".');
    return defaultConfig;
  }

  const customConfig = require(customConfigPath); // eslint-disable-line

  if (typeof customConfig === 'function') {
    logger.info('=> Loading custom webpack config (full-control mode).');
    return customConfig(config, configType, defaultConfig, configDir);
  }

  logger.info('=> Loading custom webpack config.');

  customConfig.module = customConfig.module || {};

  return {
    ...customConfig,
    // We'll always load our configurations after the custom config.
    // So, we'll always load the stuff we need.
    ...config,
    // We need to use our and custom plugins.
    plugins: [...config.plugins, ...(customConfig.plugins || [])],
    module: {
      ...config.module,
      // We need to use our and custom rules.
      ...customConfig.module,
      rules: [...config.module.rules, ...(customConfig.module.rules || [])],
    },
  };
}
Пример #22
0
      }
    ],
    loaders: [
      // Process JS with Babel.
      {
        test: /\.(js|jsx)$/,
        include: paths.appSrc,
        loader: "babel",
        query: {

          // This is a feature of `babel-loader` for webpack (not Babel itself).
          // It enables caching results in ./node_modules/.cache/react-scripts/
          // directory for faster rebuilds. We use findCacheDir() because of:
          // https://github.com/facebookincubator/create-react-app/issues/483
          cacheDirectory: findCacheDir({
            name: "react-scripts"
          })
        }
      },
      // "postcss" loader applies autoprefixer to our CSS.
      // "css" loader resolves paths in CSS and adds assets as dependencies.
      // "style" loader turns CSS into JS modules that inject <style> tags.
      // In production, we use a plugin to extract that CSS to a file, but
      // in development "style" loader enables hot editing of CSS.
      {
        test: /\.css$/,
        loader: "style!css!postcss"
      },
      {
        test: /\.styl$/,
        loader: "style!css!postcss!stylus"
Пример #23
0
            }
        ],
        loaders: [
            // Process JS with Babel.
            {
                test: /\.(js|jsx)$/,
                include: paths.appSrc,
                loader: 'babel',
                query: {

                    // This is a feature of `babel-loader` for webpack (not Babel itself).
                    // It enables caching results in ./node_modules/.cache/react-scripts/
                    // directory for faster rebuilds. We use findCacheDir() because of:
                    // https://github.com/facebookincubator/create-react-app/issues/483
                    cacheDirectory: findCacheDir({
                        name: 'react-scripts'
                    })
                }
            },
            // "postcss" loader applies autoprefixer to our CSS.
            // "css" loader resolves paths in CSS and adds assets as dependencies.
            // "style" loader turns CSS into JS modules that inject <style> tags.
            // In production, we use a plugin to extract that CSS to a file, but
            // in development "style" loader enables hot editing of CSS.
            {
                test: /\.scss$/,
                loader: 'style!css!postcss!sass'
            },
            // JSON is not enabled by default in Webpack but both Node and Browserify
            // allow it implicitly so we also enable it.
            {
Пример #24
0
// `baseConfig` is a webpack configuration bundled with storybook.
// Storybook will look in the `configDir` directory
// (inside working directory) if a config path is not provided.
export default function(configType, baseConfig, configDir) {
  const config = baseConfig;

  const babelConfig = loadBabelConfig(configDir);
  config.module.rules[0].query = {
    // This is a feature of `babel-loader` for webpack (not Babel itself).
    // It enables a cache directory for faster-rebuilds
    // `find-cache-dir` will create the cache directory under the node_modules directory.
    cacheDirectory: findCacheDir({ name: 'react-storybook' }),
    ...babelConfig,
  };

  // Check whether a config.js file exists inside the storybook
  // config directory and throw an error if it's not.
  const storybookConfigPath = path.resolve(configDir, 'config.js');
  if (!fs.existsSync(storybookConfigPath)) {
    const err = new Error(`=> Create a storybook config file in "${configDir}/config.js".`);
    throw err;
  }
  config.entry.preview.push(require.resolve(storybookConfigPath));

  // Check whether addons.js file exists inside the storybook.
  // Load the default addons.js file if it's missing.
  const storybookDefaultAddonsPath = path.resolve(__dirname, 'addons.js');
  const storybookCustomAddonsPath = path.resolve(configDir, 'addons.js');
  if (fs.existsSync(storybookCustomAddonsPath)) {
    logger.info('=> Loading custom addons config.');
    config.entry.manager.unshift(storybookCustomAddonsPath);
  } else {
    config.entry.manager.unshift(storybookDefaultAddonsPath);
  }

  // Check whether user has a custom webpack config file and
  // return the (extended) base configuration if it's not available.
  const customConfigPath = path.resolve(configDir, 'webpack.config.js');

  if (!fs.existsSync(customConfigPath)) {
    logger.info('=> Using default webpack setup based on "Create React App".');
    const configPath = path.resolve(__dirname, './config/defaults/webpack.config.js');
    const customConfig = require(configPath);

    return customConfig(config);
  }
  const customConfig = require(customConfigPath);

  if (typeof customConfig === 'function') {
    logger.info('=> Loading custom webpack config (full-control mode).');
    return customConfig(config, configType);
  }
  logger.info('=> Loading custom webpack config (extending mode).');
  return {
    ...customConfig,
    // We'll always load our configurations after the custom config.
    // So, we'll always load the stuff we need.
    ...config,
    // Override with custom devtool if provided
    devtool: customConfig.devtool || config.devtool,
    // We need to use our and custom plugins.
    plugins: [...config.plugins, ...(customConfig.plugins || [])],
    module: {
      ...config.module,
      // We need to use our and custom rules.
      ...customConfig.module,
      rules: [
        ...config.module.rules,
        ...((customConfig.module && customConfig.module.rules) || []),
      ],
    },
    resolve: {
      ...config.resolve,
      ...customConfig.resolve,
      alias: {
        ...config.alias,
        ...(customConfig.resolve && customConfig.resolve.alias),
      },
    },
  };
}