Socket
Socket
Sign inDemoInstall

ember-cli-babel

Package Overview
Dependencies
Maintainers
5
Versions
154
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ember-cli-babel - npm Package Compare versions

Comparing version 7.23.0 to 7.24.0-beta.1

lib/babel-options-util.js

8

CHANGELOG.md

@@ -0,1 +1,9 @@

## v7.24.0-beta.1 (2021-01-19)
#### :rocket: Enhancement
* [#371](https://github.com/babel/ember-cli-babel/pull/371) Adds support for babel config file ([@suchitadoshi1987](https://github.com/suchitadoshi1987))
#### Committers: 1
- Suchita Doshi ([@suchitadoshi1987](https://github.com/suchitadoshi1987))
## v7.23.0 (2020-10-15)

@@ -2,0 +10,0 @@

540

index.js
'use strict';
const {
_shouldCompileModules,
_shouldIncludeHelpers,
_shouldHandleTypeScript,
_getExtensions,
_parentName,
_shouldHighlightCode,
} = require("./lib/babel-options-util");
const VersionChecker = require('ember-cli-version-checker');
const clone = require('clone');
const babel = require('@babel/core');
const path = require('path');
const semver = require('semver');
const defaultShouldIncludeHelpers = require('./lib/default-should-include-helpers');
const getBabelOptions = require('./lib/get-babel-options');
const findApp = require('./lib/find-app');
const emberPlugins = require('./lib/ember-plugins');

@@ -18,2 +27,5 @@ const APP_BABEL_RUNTIME_VERSION = new WeakMap();

configKey: 'ember-cli-babel',
// Note: This is not used internally for this addon, this is added for users to import this function for getting the ember specific
// babel plugins. Eg: adding ember specific babel plugins in their babel.config.js.
buildEmberPlugins: emberPlugins,

@@ -27,3 +39,3 @@ init() {

if (dep.lt('2.13.0')) {
throw new Error(`ember-cli-babel@7 (used by ${this._parentName()} at ${this.parent.root}) cannot be used by ember-cli versions older than 2.13, you used ${dep.version}`);
throw new Error(`ember-cli-babel@7 (used by ${_parentName(this.parent)} at ${this.parent.root}) cannot be used by ember-cli versions older than 2.13, you used ${dep.version}`);
}

@@ -34,4 +46,3 @@ },

let config = _config || this._getAddonOptions();
return this._getBabelOptions(config);
return getBabelOptions(config, this);
},

@@ -41,3 +52,3 @@

if (!this._cachedDebugTree) {
this._cachedDebugTree = require('broccoli-debug').buildDebugCallback(`ember-cli-babel:${this._parentName()}`);
this._cachedDebugTree = require('broccoli-debug').buildDebugCallback(`ember-cli-babel:${_parentName(this.parent)}`);
}

@@ -48,10 +59,77 @@

/**
* Default babel options
* @param {*} config
*/
_getDefaultBabelOptions(config = {}) {
let emberCLIBabelConfig = config["ember-cli-babel"];
let providedAnnotation;
let throwUnlessParallelizable;
let sourceMaps = false;
let shouldCompileModules = _shouldCompileModules(config, this.project);
if (emberCLIBabelConfig) {
providedAnnotation = emberCLIBabelConfig.annotation;
throwUnlessParallelizable = emberCLIBabelConfig.throwUnlessParallelizable;
}
if (config.babel && "sourceMaps" in config.babel) {
sourceMaps = config.babel.sourceMaps;
}
let options = {
annotation: providedAnnotation || `Babel: ${_parentName(this.parent)}`,
sourceMaps,
throwUnlessParallelizable,
filterExtensions: _getExtensions(config, this.parent),
plugins: []
};
if (shouldCompileModules) {
options.moduleIds = true;
options.getModuleId = require("./lib/relative-module-paths").getRelativeModulePath;
}
options.highlightCode = _shouldHighlightCode(this.parent);
options.babelrc = false;
options.configFile = false;
return options;
},
transpileTree(inputTree, _config) {
let config = _config || this._getAddonOptions();
let description = `000${++count}`.slice(-3);
let postDebugTree = this._debugTree(inputTree, `${description}:input`);
let options = this._getDefaultBabelOptions(config);
let output;
let options = this.buildBabelOptions(config);
let output;
if (this._shouldDoNothing(options)) {
const customAddonConfig = config['ember-cli-babel'];
const shouldUseBabelConfigFile = customAddonConfig && customAddonConfig.useBabelConfig;
if (shouldUseBabelConfigFile) {
let babelConfig = babel.loadPartialConfig({
root: this.parent.root,
rootMode: 'root',
envName: process.env.EMBER_ENV || process.env.BABEL_ENV || process.env.NODE_ENV || "development",
});
if (babelConfig.config === undefined) {
// should contain the file that we used for the config,
// if it is undefined then we didn't find any config and
// should error
throw new Error(
"Missing babel config file in the project root. Please double check if the babel config file exists or turn off the `useBabelConfig` option in your ember-cli-build.js file."
);
}
// If the babel config file is found, then pass the path into the options for the transpiler
// parse and leverage the same.
options = Object.assign({}, options, { configFile: babelConfig.config });
} else {
options = Object.assign({}, options, this.buildBabelOptions(config));
}
if (!shouldUseBabelConfigFile && this._shouldDoNothing(options)) {
output = postDebugTree;

@@ -62,3 +140,3 @@ } else {

if (this._shouldHandleTypeScript(config)) {
if (_shouldHandleTypeScript(config, this.parent)) {
let Funnel = require('broccoli-funnel');

@@ -68,3 +146,2 @@ let inputWithoutDeclarations = new Funnel(transpilationInput, { exclude: ['**/*.d.ts'] });

}
output = new BabelTranspiler(transpilationInput, options);

@@ -79,3 +156,3 @@ }

name: 'ember-cli-babel',
ext: this._getExtensions(this._getAddonOptions()),
ext: _getExtensions(this._getAddonOptions(), this.parent),
toTree: (tree) => this.transpileTree(tree)

@@ -109,32 +186,2 @@ });

_shouldIncludeHelpers(options) {
let appOptions = this._getAppOptions();
let customOptions = appOptions['ember-cli-babel'];
let shouldIncludeHelpers = false;
if (!this._shouldCompileModules(options)) {
// we cannot use external helpers if we are not transpiling modules
return false;
} else if (customOptions && 'includeExternalHelpers' in customOptions) {
shouldIncludeHelpers = customOptions.includeExternalHelpers === true;
} else {
// Check the project to see if we should include helpers based on heuristics.
shouldIncludeHelpers = defaultShouldIncludeHelpers(this.project);
}
let appEmberCliBabelPackage = this.project.addons.find(a => a.name === 'ember-cli-babel').pkg;
let appEmberCliBabelVersion = appEmberCliBabelPackage && appEmberCliBabelPackage.version;
if (appEmberCliBabelVersion && semver.gte(appEmberCliBabelVersion, '7.3.0-beta.1')) {
return shouldIncludeHelpers;
} else if (shouldIncludeHelpers) {
this.project.ui.writeWarnLine(
`${this._parentName()} attempted to include external babel helpers to make your build size smaller, but your root app's ember-cli-babel version is not high enough. Please update ember-cli-babel to v7.3.0-beta.1 or later.`
);
}
return false;
},
_getHelperVersion() {

@@ -166,3 +213,3 @@ if (!APP_BABEL_RUNTIME_VERSION.has(this.project)) {

let isRootBabel = this.parent === this.project;
let shouldIncludeHelpers = isRootBabel && this._shouldIncludeHelpers(this._getAppOptions());
let shouldIncludeHelpers = isRootBabel && _shouldIncludeHelpers(this._getAppOptions(), this);

@@ -246,306 +293,2 @@ if (!shouldIncludeHelpers) { return; }

_parentName() {
let parentName;
if (this.parent) {
if (typeof this.parent.name === 'function') {
parentName = this.parent.name();
} else {
parentName = this.parent.name;
}
}
return parentName;
},
_getAddonProvidedConfig(addonOptions) {
let options = clone(addonOptions.babel || {});
let plugins = options.plugins || [];
let postTransformPlugins = options.postTransformPlugins || [];
return {
options,
plugins,
postTransformPlugins
};
},
_getExtensions(config) {
let shouldHandleTypeScript = this._shouldHandleTypeScript(config);
let emberCLIBabelConfig = config['ember-cli-babel'] || {};
return emberCLIBabelConfig.extensions || (shouldHandleTypeScript ? ['js', 'ts'] : ['js']);
},
_getBabelOptions(config) {
let addonProvidedConfig = this._getAddonProvidedConfig(config);
let shouldCompileModules = this._shouldCompileModules(config);
let shouldIncludeHelpers = this._shouldIncludeHelpers(config);
let shouldHandleTypeScript = this._shouldHandleTypeScript(config);
let shouldIncludeDecoratorPlugins = this._shouldIncludeDecoratorPlugins(config);
let emberCLIBabelConfig = config['ember-cli-babel'];
let shouldRunPresetEnv = true;
let providedAnnotation;
let throwUnlessParallelizable;
if (emberCLIBabelConfig) {
providedAnnotation = emberCLIBabelConfig.annotation;
shouldRunPresetEnv = !emberCLIBabelConfig.disablePresetEnv;
throwUnlessParallelizable = emberCLIBabelConfig.throwUnlessParallelizable;
}
let sourceMaps = false;
if (config.babel && 'sourceMaps' in config.babel) {
sourceMaps = config.babel.sourceMaps;
}
let filterExtensions = this._getExtensions(config);
let options = {
annotation: providedAnnotation || `Babel: ${this._parentName()}`,
sourceMaps,
throwUnlessParallelizable,
filterExtensions
};
let userPlugins = addonProvidedConfig.plugins;
let userPostTransformPlugins = addonProvidedConfig.postTransformPlugins;
if (shouldHandleTypeScript) {
userPlugins = this._addTypeScriptPlugin(userPlugins.slice(), addonProvidedConfig.options);
}
if (shouldIncludeDecoratorPlugins) {
userPlugins = this._addDecoratorPlugins(userPlugins.slice(), addonProvidedConfig.options, config);
}
options.plugins = [].concat(
shouldIncludeHelpers && this._getHelpersPlugin(),
userPlugins,
this._getDebugMacroPlugins(config),
this._getEmberModulesAPIPolyfill(config),
this._getEmberDataPackagesPolyfill(config),
shouldCompileModules && this._getModulesPlugin(),
userPostTransformPlugins
).filter(Boolean);
options.presets = [
shouldRunPresetEnv && this._getPresetEnv(addonProvidedConfig),
].filter(Boolean);
if (shouldCompileModules) {
options.moduleIds = true;
options.getModuleId = require('./lib/relative-module-paths').getRelativeModulePath;
}
options.highlightCode = this._shouldHighlightCode();
options.babelrc = false;
return options;
},
_shouldHandleTypeScript(config) {
let emberCLIBabelConfig = config['ember-cli-babel'] || {};
if (typeof emberCLIBabelConfig.enableTypeScriptTransform === 'boolean') {
return emberCLIBabelConfig.enableTypeScriptTransform;
}
let typeScriptAddon = this.parent.addons
&& this.parent.addons.find(a => a.name === 'ember-cli-typescript');
return typeof typeScriptAddon !== 'undefined'
&& semver.gte(typeScriptAddon.pkg.version, '4.0.0-alpha.1');
},
_buildClassFeaturePluginConstraints(constraints, config) {
// With versions of ember-cli-typescript < 4.0, class feature plugins like
// @babel/plugin-proposal-class-properties were run before the TS transform.
if (!this._shouldHandleTypeScript(config)) {
constraints.before = constraints.before || [];
constraints.before.push('@babel/plugin-transform-typescript');
}
return constraints;
},
_addTypeScriptPlugin(plugins) {
const { hasPlugin, addPlugin } = require('ember-cli-babel-plugin-helpers');
if (hasPlugin(plugins, '@babel/plugin-transform-typescript')) {
if (this.parent === this.project) {
this.project.ui.writeWarnLine(`${
this._parentName()
} has added the TypeScript transform plugin to its build, but ember-cli-babel provides this by default now when ember-cli-typescript >= 4.0 is installed! You can remove the transform, or the addon that provided it.`);
}
} else {
addPlugin(
plugins,
[
require.resolve('@babel/plugin-transform-typescript'),
{ allowDeclareFields: true },
],
{
before: [
'@babel/plugin-proposal-class-properties',
'@babel/plugin-proposal-private-methods',
'@babel/plugin-proposal-decorators',
]
}
);
}
return plugins;
},
_shouldIncludeDecoratorPlugins(config) {
let customOptions = config['ember-cli-babel'] || {};
return customOptions.disableDecoratorTransforms !== true;
},
_addDecoratorPlugins(plugins, options, config) {
const { hasPlugin, addPlugin } = require('ember-cli-babel-plugin-helpers');
if (hasPlugin(plugins, '@babel/plugin-proposal-decorators')) {
if (this.parent === this.project) {
this.project.ui.writeWarnLine(`${
this._parentName()
} has added the decorators plugin to its build, but ember-cli-babel provides these by default now! You can remove the transforms, or the addon that provided them, such as @ember-decorators/babel-transforms. Ember supports the stage 1 decorator spec and transforms, so if you were using stage 2, you'll need to ensure that your decorators are compatible, or convert them to stage 1.`);
}
} else {
addPlugin(
plugins,
[require.resolve('@babel/plugin-proposal-decorators'), { legacy: true }],
this._buildClassFeaturePluginConstraints({
before: ['@babel/plugin-proposal-class-properties']
}, config)
);
}
if (hasPlugin(plugins, '@babel/plugin-proposal-class-properties')) {
if (this.parent === this.project) {
this.project.ui.writeWarnLine(`${
this._parentName()
} has added the class-properties plugin to its build, but ember-cli-babel provides these by default now! You can remove the transforms, or the addon that provided them, such as @ember-decorators/babel-transforms.`);
}
} else {
addPlugin(
plugins,
[require.resolve('@babel/plugin-proposal-class-properties'), { loose: options.loose || false }],
this._buildClassFeaturePluginConstraints({
after: ['@babel/plugin-proposal-decorators']
}, config)
);
}
if (hasPlugin(plugins, 'babel-plugin-filter-imports')) {
let checker = new VersionChecker(this.parent).for('babel-plugin-filter-imports', 'npm');
if (checker.lt('3.0.0')) {
addPlugin(
plugins,
require.resolve('./lib/dedupe-internal-decorators-plugin'),
{
after: ['babel-plugin-filter-imports']
}
);
}
}
return plugins;
},
_getDebugMacroPlugins(config) {
let addonOptions = config['ember-cli-babel'] || {};
if (addonOptions.disableDebugTooling) {
return;
}
const isProduction = process.env.EMBER_ENV === 'production';
const isDebug = !isProduction;
return [
[
require.resolve('babel-plugin-debug-macros'),
{
flags: [
{
source: '@glimmer/env',
flags: { DEBUG: isDebug, CI: !!process.env.CI },
},
],
externalizeHelpers: {
global: 'Ember',
},
debugTools: {
isDebug,
source: '@ember/debug',
assertPredicateIndex: 1,
},
},
'@ember/debug stripping',
],
[
require.resolve('babel-plugin-debug-macros'),
{
// deprecated import path https://github.com/emberjs/ember.js/pull/17926#issuecomment-484987305
externalizeHelpers: {
global: 'Ember',
},
debugTools: {
isDebug,
source: '@ember/application/deprecations',
assertPredicateIndex: 1,
},
},
'@ember/application/deprecations stripping',
],
];
},
_getEmberModulesAPIPolyfill(config) {
let addonOptions = config['ember-cli-babel'] || {};
if (addonOptions.disableEmberModulesAPIPolyfill) { return; }
if (this._emberVersionRequiresModulesAPIPolyfill()) {
const ignore = this._getEmberModulesAPIIgnore();
return [[require.resolve('babel-plugin-ember-modules-api-polyfill'), { ignore }]];
}
},
_getEmberDataPackagesPolyfill(config) {
let addonOptions = config['ember-cli-babel'] || {};
if (addonOptions.disableEmberDataPackagesPolyfill) { return; }
// Don't convert ember-data itself or any @ember-data packages!
if (typeof this.parent.name === 'string' && (this.parent.name === 'ember-data' || this.parent.name.startsWith('@ember-data/'))) { return; }
if (this._emberDataVersionRequiresPackagesPolyfill()) {
return [[require.resolve('babel-plugin-ember-data-packages-polyfill')]];
}
},
_getPresetEnv(config) {
let options = config.options;
let targets = this.project && this.project.targets;
let presetOptions = Object.assign({}, options, {
modules: false,
targets
});
// delete any properties added to `options.babel` that
// are invalid for @babel/preset-env
delete presetOptions.sourceMaps;
delete presetOptions.plugins;
delete presetOptions.postTransformPlugins;
return [require.resolve('@babel/preset-env'), presetOptions];
},
_getTargets() {

@@ -569,11 +312,2 @@ let targets = this.project && this.project.targets;

_getModulesPlugin() {
const resolvePath = require('./lib/relative-module-paths').resolveRelativeModulePath;
return [
[require.resolve('babel-plugin-module-resolver'), { resolvePath }],
[require.resolve('@babel/plugin-transform-modules-amd'), { noInterop: true }],
];
},
/*

@@ -587,95 +321,5 @@ * Used to discover if the addon's current configuration will compile modules

shouldCompileModules() {
return this._shouldCompileModules(this._getAddonOptions());
return _shouldCompileModules(this._getAddonOptions(), this.project);
},
// will use any provided configuration
_shouldCompileModules(options) {
let addonOptions = options['ember-cli-babel'];
if (addonOptions && 'compileModules' in addonOptions) {
return addonOptions.compileModules;
} else {
return semver.gt(this.project.emberCLIVersion(), '2.12.0-alpha.1');
}
},
_emberVersionRequiresModulesAPIPolyfill() {
// once a version of Ember ships with the
// emberjs/rfcs#176 modules natively this will
// be updated to detect that and return false
return true;
},
_emberDataVersionRequiresPackagesPolyfill() {
let checker = new VersionChecker(this.project);
let dep = checker.for('ember-data');
let hasEmberData = dep.exists();
if (hasEmberData) {
if (!dep.version) {
throw new Error('EmberData missing version');
}
return semver.lt(dep.version, '3.12.0-alpha.0');
}
return false;
},
_getEmberModulesAPIIgnore() {
const ignore = {
'@ember/debug': ['assert', 'deprecate', 'warn'],
'@ember/application/deprecations': ['deprecate'],
};
if (this._shouldIgnoreEmberString()) {
ignore['@ember/string'] = [
'fmt', 'loc', 'w',
'decamelize', 'dasherize', 'camelize',
'classify', 'underscore', 'capitalize',
'setStrings', 'getStrings', 'getString'
];
}
if (this._shouldIgnoreJQuery()) {
ignore['jquery'] = ['default'];
}
return ignore;
},
_isProjectName(dependency) {
return this.project.name && this.project.name() === dependency;
},
_isTransitiveDependency(dependency) {
return (
!(dependency in this.parent.dependencies()) &&
!(dependency in this.project.dependencies())
)
},
_shouldIgnoreEmberString() {
let packageName = '@ember/string';
if (this._isProjectName(packageName)) { return true; }
if (this._isTransitiveDependency(packageName)) { return false; }
let checker = new VersionChecker(this.parent).for(packageName, 'npm');
return checker.exists();
},
_shouldIgnoreJQuery() {
let packageName = '@ember/jquery';
if (this._isProjectName(packageName)) { return true; }
if (this._isTransitiveDependency(packageName)) { return false; }
let checker = new VersionChecker(this.parent).for(packageName, 'npm');
return checker.gte('0.6.0');
},
_shouldHighlightCode() {
let checker = new VersionChecker(this.parent).for('broccoli-middleware', 'npm');
return checker.gte('2.1.0');
},
// detect if running babel would do nothing... and do nothing instead

@@ -682,0 +326,0 @@ _shouldDoNothing(options) {

{
"name": "ember-cli-babel",
"version": "7.23.0",
"version": "7.24.0-beta.1",
"description": "Ember CLI addon for Babel",

@@ -67,2 +67,3 @@ "keywords": [

"fixturify-project": "^1.10.0",
"resolve-package-path": "^3.1.0",
"rimraf": "^3.0.1",

@@ -69,0 +70,0 @@ "semver": "^5.5.0"

@@ -21,2 +21,3 @@ # ember-cli-babel

+ [Enabling TypeScript Transpilation](#enabling-typescript-transpilation)
* [Babel config file usage](#babel-config-usage)
* [Addon usage](#addon-usage)

@@ -295,3 +296,71 @@ + [Adding Custom Plugins](#adding-custom-plugins)

```
### Babel config usage
If you want to use the existing babel config from your project instead of the auto-generated one from this addon, then you would need to *opt-in* by passing the config `useBabelConfig: true` as a child property of `ember-cli-babel` in your `ember-cli-build.js` file.
*Note: If you are using this option, then you have to make sure that you are adding all of the required plugins required for Ember to transpile correctly.*
Example usage:
```js
//ember-cli-build.js
let app = new EmberAddon(defaults, {
"ember-cli-babel": {
useBabelConfig: true,
// ember-cli-babel related options
},
});
```
```js
//babel.config.js
const { buildEmberPlugins } = require("ember-cli-babel");
module.exports = function (api) {
api.cache(true);
return {
presets: [
[
require.resolve("@babel/preset-env"),
{
targets: require("./config/targets"),
},
],
],
plugins: [
// if you want external helpers
[
require.resolve("@babel/plugin-transform-runtime"),
{
version: require("@babel/plugin-transform-runtime/package").version,
regenerator: false,
useESModules: true,
},
],
// this is where all the ember required plugins would reside
...buildEmberPlugins(__dirname, { /*customOptions if you want to pass in */ }),
],
};
};
```
#### Ember Plugins
Ember Plugins is a helper function that returns a list of plugins that are required for transpiling Ember correctly. You can import this helper function and add it to your existing `babel.config` file.
The first argument is **required** which is the path to the root of your project (generally `__dirname`).
**Config options:**
```js
{
disableModuleResolution: boolean, // determines if you want the module resolution enabled
emberDataVersionRequiresPackagesPolyfill: boolean, // enable ember data's polyfill
shouldIgnoreJQuery: boolean, // ignore jQuery
shouldIgnoreEmberString: boolean, // ignore ember string
shouldIgnoreDecoratorAndClassPlugins: boolean, // disable decorator plugins
disableEmberModulesAPIPolyfill: boolean, // disable ember modules API polyfill
}
```
### Addon usage

@@ -298,0 +367,0 @@

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc