Socket
Socket
Sign inDemoInstall

ember-cli-bundle-analyzer

Package Overview
Dependencies
144
Maintainers
3
Versions
11
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.3.0 to 1.0.0

create-config.js

11

CHANGELOG.md

@@ -0,1 +1,12 @@

## v1.0.0 (2023-02-08)
#### :boom: Breaking Change
* [#26](https://github.com/simonihmig/ember-cli-bundle-analyzer/pull/26) Refactor to use `source-map-explorer`, enabling usage with Ember CLI, ember-auto-import and Embroider ([@simonihmig](https://github.com/simonihmig))
#### :rocket: Enhancement
* [#26](https://github.com/simonihmig/ember-cli-bundle-analyzer/pull/26) Refactor to use `source-map-explorer`, enabling usage with Ember CLI, ember-auto-import and Embroider ([@simonihmig](https://github.com/simonihmig))
#### Committers: 1
- Simon Ihmig ([@simonihmig](https://github.com/simonihmig))
## v0.3.0 (2022-12-29)

@@ -2,0 +13,0 @@

252

index.js

@@ -5,15 +5,8 @@ 'use strict';

const debug = require('debug')('ember-cli-bundle-analyzer');
const { createOutput, summarizeAll } = require('broccoli-concat-analyser');
const fs = require('fs');
const sane = require('sane');
const touch = require('touch');
const hashFiles = require('hash-files').sync;
const tmp = require('tmp');
const VersionChecker = require('ember-cli-version-checker');
const interceptStdout = require('intercept-stdout');
const injectLivereload = require('./lib/inject-livereload');
const explore = require('source-map-explorer').explore;
const glob = require('fast-glob');
const REQUEST_PATH = '/_analyze';
const BROCCOLI_CONCAT_PATH_SUPPORT = '3.6.0';
const BROCCOLI_CONCAT_LAZY_SUPPORT = '3.7.0';

@@ -29,2 +22,7 @@ module.exports = {

_buildPromise: null,
bundleFiles: [
'dist/assets/*.js',
// ignore CSS files for now, due to https://github.com/ember-cli/ember-cli/issues/9384
// 'dist/assets/*.css'
],

@@ -34,11 +32,2 @@ init() {

debug(`${this.name} started.`);
let checker = new VersionChecker(this);
this.concatVersion = checker.for('broccoli-concat');
if (this.concatVersion.lt(BROCCOLI_CONCAT_LAZY_SUPPORT)) {
debug(`broccoli-concat v${this.concatVersion.version} does not support lazy stats activation, forced to activate prematurely.`);
this.enableStats();
}
this.initConcatStatsPath();
},

@@ -48,6 +37,9 @@

this._super.included.apply(this, arguments);
// this.app = app;
let options = app.options['bundle-analyzer'] || {};
let ignoredFiles = options && options.ignore || [];
this.checkSourcemapConfigs();
let options = app.options['bundleAnalyzer'] || {};
this.analyzerOptions = options;
let ignoredFiles = (options && options.ignore) || [];
if (!Array.isArray(ignoredFiles)) {

@@ -57,8 +49,8 @@ ignoredFiles = [ignoredFiles];

// it seems ember itself bundles its files before they are added to vender.js, which causes concat stats to be
// generated which are irrelevant to the final bundle. So exclude them...
ignoredFiles = ignoredFiles.concat('ember.js', 'ember-testing.js');
if (options.ignoreTestFiles !== false) {
ignoredFiles = ignoredFiles.concat('tests.js', 'test-support.js', 'test-support.css', '*-test.js');
ignoredFiles = ignoredFiles.concat(
'tests.js',
'test-support.js',
'test-support.css'
);
}

@@ -69,10 +61,29 @@

initConcatStatsPath() {
// if broccoli-concat supports a custom path for stats data, put the data in a temp folder outside of the project!
if (this.concatVersion.gte(BROCCOLI_CONCAT_PATH_SUPPORT)) {
this.concatStatsPath = tmp.dirSync().name;
process.env.CONCAT_STATS_PATH = this.concatStatsPath;
} else {
this.concatStatsPath = path.join(process.cwd(), 'concat-stats-for');
checkSourcemapConfigs() {
if (!this.isEnabled()) {
return;
}
const emberCliSupport = this.app.options.sourcemaps?.enabled;
const emberAutoImportSupport =
this.app.options.autoImport?.webpack?.devtool;
// @todo Embroider detection
if (!emberCliSupport) {
this.ui.writeWarnLine(
'ember-cli-bundle-analyzer requires source maps to be enabled, but they are turned off for Ember CLI. Please see https://github.com/simonihmig/ember-cli-bundle-analyzer#source-maps for how to enable them!'
);
}
if (emberAutoImportSupport !== 'source-map') {
if (!emberAutoImportSupport) {
this.ui.writeWarnLine(
`ember-cli-bundle-analyzer requires fully enabled source maps for ember-auto-import, but they are turned off. Please see https://github.com/simonihmig/ember-cli-bundle-analyzer#source-maps for how to enable them!`
);
} else {
this.ui.writeWarnLine(
`ember-cli-bundle-analyzer requires fully enabled source maps for ember-auto-import, but the config is set to "${emberAutoImportSupport}". Please see https://github.com/simonihmig/ember-cli-bundle-analyzer#source-maps for how to enable them!`
);
}
}
},

@@ -89,59 +100,67 @@

app.get(REQUEST_PATH, (req, res) => {
app.get(REQUEST_PATH, async (req, res) => {
this.debugRequest(req);
this.initBuildWatcher();
Promise.resolve()
.then(() => this._buildPromise)
.then(() => {
if (!this.hasStats()) {
res.sendFile(path.join(__dirname, 'lib', 'output', 'computing', 'index.html'));
return;
}
if (!this._statsOutput) {
res.sendFile(path.join(__dirname, 'lib', 'output', 'computing', 'index.html'));
} else {
res.send(this._statsOutput);
}
});
await this._buildPromise;
if (!this._statsOutput) {
res.sendFile(
path.join(__dirname, 'lib', 'output', 'computing', 'index.html')
);
} else {
res.send(this._statsOutput);
}
});
app.get(`${REQUEST_PATH}/compute`, (req, res) => {
this.initWatcher();
app.get(`${REQUEST_PATH}/compute`, async (req, res) => {
this.debugRequest(req);
this.initBuildWatcher();
Promise.resolve()
.then(() => this._buildPromise)
.then(() => {
if (!this.hasStats()) {
this.enableStats();
this.triggerBuild();
return this._initialBuildPromise;
}
})
.then(() => {
// @todo make this throw an exception when there are no stats
this.computeOutput()
.then((output) => {
this._statsOutput = injectLivereload(output);
res.redirect(REQUEST_PATH);
})
.catch((e) => {
this.ui.writeError(e);
res.sendFile(path.join(__dirname, 'lib', 'output', 'no-stats', 'index.html'));
});
})
.catch(e => {
await this._buildPromise;
try {
let output = await this.computeOutput();
this._statsOutput = injectLivereload(output);
res.redirect(REQUEST_PATH);
} catch (e) {
if (e.errors) {
e.errors.map((e) => this.ui.writeError(e.error));
} else {
this.ui.writeError(e);
});
}
res.sendFile(
path.join(__dirname, 'lib', 'output', 'no-stats', 'index.html')
);
}
});
},
computeOutput() {
debugRequest(req) {
debug(`${req.method} ${req.url}`);
},
async computeOutput() {
if (!this._computePromise) {
debug('Computing stats...');
this._computePromise = summarizeAll(this.concatStatsPath, this.ignoredFiles)
.then(() => {
debug('Computing finished.');
this._computePromise = null;
return createOutput(this.concatStatsPath);
});
let files = await glob(this.bundleFiles, {
ignore: this.ignoredFiles.map((file) => `dist/assets/${file}`),
});
debug('Found these bundles: ' + files.join(', '));
this._computePromise = explore(files, {
output: { format: 'html' },
replaceMap: { 'dist/': '', 'webpack://__ember_auto_import__/': '' },
noBorderChecks: true,
}).then((result) => {
debug(
'Computing finished, bundle results: ' +
JSON.stringify(result.bundles)
);
result.errors.map((e) =>
this.ui[e.isWarning ? 'writeWarnLine' : 'writeErrorLine'](
`${e.bundleName}: ${e.message}`
)
);
this._computePromise = null;
return result.output;
});
}

@@ -153,7 +172,5 @@ return this._computePromise;

let resolve;
let initialResolve;
if (this._buildWatcher) {
return;
}
this._initialBuildPromise = new Promise((_resolve) => initialResolve = _resolve);
this._buildWatcher = interceptStdout((text) => {

@@ -169,10 +186,13 @@ if (text instanceof Buffer) {

debug('Rebuild detected');
this._buildPromise = new Promise((_resolve) => resolve = _resolve);
this._buildPromise = new Promise((_resolve) => (resolve = _resolve));
this._statsOutput = null;
}
if (text.match(/Build successful/)) {
if (!resolve) {
return;
}
debug('Finished build detected');
setTimeout(() => {
resolve();
initialResolve();
}, 1000);

@@ -183,67 +203,5 @@ }

initWatcher() {
if (this._hasWatcher) {
return;
}
debug('Initializing watcher on json files');
let watcher = sane(this.concatStatsPath, { glob: ['*.json'], ignored: ['*.out.json'] });
watcher.on('change', this._handleWatcher.bind(this));
watcher.on('add', this._handleWatcher.bind(this));
watcher.on('delete', this._handleWatcher.bind(this));
this._hasWatcher = true;
},
_handleWatcher(filename, root/*, stat*/) {
let file = path.join(root, filename);
let hash = hashFiles({ files: [file] });
if (this._hashedFiles[filename] !== hash) {
debug(`Cache invalidated by ${filename}`);
this._statsOutput = null;
this._hashedFiles[filename] = hash;
}
},
isEnabled() {
return true;
return this.app.options['bundleAnalyzer']?.enabled === true;
},
hasStats() {
return !!process.env.CONCAT_STATS && this.concatStatsPath && fs.existsSync(this.concatStatsPath);
},
enableStats() {
debug('Enabled stats generation');
process.env.CONCAT_STATS = 'true';
},
triggerBuild() {
debug('Triggering build');
let mainFile = this.getMainFile();
if (mainFile) {
debug(`Touching ${mainFile}`);
touch(mainFile);
} else {
throw new Error('No main file found to trigger build');
}
},
getMainFile() {
let { root } = this.project;
let mainCandidates = [
'app/app.js', // app
'src/main.js', // MU
'tests/dummy/app/app.js', // addon dummy app
'app/app.ts', // app (TS)
'src/main.ts', // MU (TS)
'tests/dummy/app/app.ts' // addon dummy app (TS)
]
.map((item) => path.join(root, item));
for (let mainFile of mainCandidates) {
if (fs.existsSync(mainFile)) {
return mainFile
}
}
}
};
{
"name": "ember-cli-bundle-analyzer",
"version": "0.3.0",
"version": "1.0.0",
"description": "Analyze the size and contents of your Ember app's bundles",

@@ -31,11 +31,7 @@ "keywords": [

"dependencies": {
"broccoli-concat-analyser": "^5.0.0",
"debug": "^4.3.2",
"ember-cli-version-checker": "^5.1.2",
"hash-files": "^1.1.1",
"fast-glob": "^2.2.7",
"intercept-stdout": "^0.1.2",
"node-html-light": "^1.4.0",
"sane": "^4.1.0",
"tmp": "^0.2.1",
"touch": "^3.1.0"
"source-map-explorer": "^2.5.3"
},

@@ -76,2 +72,3 @@ "devDependencies": {

"loader.js": "^4.7.0",
"lodash-es": "^4.17.11",
"mocha": "^8.4.0",

@@ -84,5 +81,2 @@ "prettier": "^2.8.1",

},
"peerDependencies": {
"ember-source": "^3.28.0 || ^4.0.0"
},
"engines": {

@@ -89,0 +83,0 @@ "node": "16.* || >= 18"

@@ -7,6 +7,5 @@ # ember-cli-bundle-analyzer

An Ember CLI addon to analyze the size and contents of your app's bundled output,
using an interactive zoomable treemap.
An Ember CLI addon to analyze the size and contents of your app's bundled output, using an interactive zoomable treemap.
View the [interactive Demo](https://cdn.rawgit.com/simonihmig/ember-cli-bundle-analyzer/bceb55a7/docs/demo.html)
View the [interactive Demo](https://raw.githack.com/simonihmig/ember-cli-bundle-analyzer/master/docs/demo.html)

@@ -17,50 +16,183 @@ ![Screenshot of analyzer output](docs/screen.png)

* analyze which individual modules make it into your final bundle
* find out how big each contained module is, including the raw source, minified and gzipped sizes
* find modules that got there by mistake
* optimize your bundle size
- analyze which individual modules make it into your final bundle
- find out how big each contained module is
- find modules that got there by mistake
- optimize your bundle size
It uses [source-map-explorer](https://github.com/danvk/source-map-explorer) under the hood,
and wraps it in an Ember CLI addon to make it easy to use.
It uses [broccoli-concat-analyser](https://github.com/stefanpenner/broccoli-concat-analyser) under the hood,
which in turn was inspired by
[webpack-bundle-analyzer](https://github.com/webpack-contrib/webpack-bundle-analyzer),
and wraps it in Ember CLI addon to make it easy to use.
Given that it works based on source maps, it is agnostic to the actual bundling tool used, be it pure Ember CLI (which is based on `broccoli-concat`), Ember CLI with ember-auto-import (which makes it a mix of `broccoli-concat` and `webpack`) or even Embroider.
The only condition is that _proper_ source maps are generated.
It uses [broccoli-concat-analyser](https://github.com/stefanpenner/broccoli-concat-analyser) under the hood,
which in turn was inspired by
[webpack-bundle-analyzer](https://github.com/webpack-contrib/webpack-bundle-analyzer),
and wraps it in Ember CLI addon to make it easy to use.
## Compatibility
* Ember CLI v3.28 or above
* Node.js v16 or above
- Ember CLI v3.28 or above
- Node.js v16 or above
- works with ember-auto-import and Embroider, as long as source maps are properly enabled
## Quick Start
## Installation
To get you going _quickly_, follow these steps:
1. Install the addon:
```
ember install ember-cli-bundle-analyzer
```
2. Setup your `ember-cli-build.js`:
```diff
const EmberApp = require('ember-cli/lib/broccoli/ember-app');
+const {
+ createEmberCLIConfig,
+} = require('ember-cli-bundle-analyzer/create-config');
module.exports = function (defaults) {
const app = new EmberApp(defaults, {
// your other options are here
// ...
+ ...createEmberCLIConfig(),
});
return app.toTree();
};
```
3. Launch your local server in analyze-mode:
```sh
ENABLE_BUNDLE_ANALYZER=true ember serve --prod
```
4. Open [http://localhost:4200/\_analyze](http://localhost:4200/_analyze)
For more detailed instructions, read the following chapters...
## Setup
Two things need to be in place for this addon to work correctly: it needs to have a [config](#Config) that at least enables it, and _proper_ [source maps](#source-maps) need to be enabled for the EmberCLI build pipeline.
While it is possible to provide these settings manually, the addon provides some recommended presets that you can apply using `createEmberCLIConfig`:
```js
// ember-cli-build.js
const EmberApp = require('ember-cli/lib/broccoli/ember-app');
const {
createEmberCLIConfig,
} = require('ember-cli-bundle-analyzer/create-config');
module.exports = function (defaults) {
const app = new EmberApp(defaults, {
// your other options are here
// ...
...createEmberCLIConfig(),
});
return app.toTree();
};
```
ember install ember-cli-bundle-analyzer
If you are using Embroider, then this should cover you:
```js
// ember-cli-build.js
const EmberApp = require('ember-cli/lib/broccoli/ember-app');
const {
createEmberCLIConfig,
createWebpackConfig,
} = require('ember-cli-bundle-analyzer/create-config');
module.exports = function (defaults) {
const app = new EmberApp(defaults, {
// your other options are here
// ...
...createEmberCLIConfig(),
});
return require('@embroider/compat').compatBuild(app, Webpack, {
// your Embroider options...
packagerOptions: {
webpackConfig: {
// any custom webpack options you might have
...createWebpackConfig(),
},
},
});
};
```
## Usage
With this config, when the environment variable `ENABLE_BUNDLE_ANALYZER` is set, it will enable the addon and apply required options to both Ember CLI and ember-auto-import to fully enable source maps with the required fidelity level.
After you have started your development server using `ember serve`, this addon adds a custom middleware listening to
`/_analyze`. So just open `http://localhost:4200/_analyze` in your web browser to access the analyzer output.
> The reason the addon is not enabled by default is that it would be pointless if not having proper source maps fully enabled as well. And this might not be what you want by default, as generating full source maps comes at a cost of increased build times. On top of that you might also want to analyze the bundles only in production mode.
While it processes the data, which can take a while due to live minification and compression of all involved modules,
a loading screen is displayed. After processing has finished you should see the final output.
Note that this might override some of your existing custom settings for source maps or ember-auto-import if you have those. So if that does not work for you, you can either try to deep merge the configs as in the following example, or provide your own explicit configs based of what [`createEmberCLIConfig` provides](./create-config.js).
Live reloading is supported, so whenever you change a project file the output will be re-computed and updated.
```js
// ember-cli-build.js
const EmberApp = require('ember-cli/lib/broccoli/ember-app');
const {
createEmberCLIConfig,
} = require('ember-cli-bundle-analyzer/create-config');
const { defaultsDeep } = require('ember-cli-lodash-subset');
### Options
module.exports = function (defaults) {
const app = new EmberApp(
defaults,
defaultsDeep(
{
// your other options are here
// ...
},
createEmberCLIConfig()
)
);
You can customize the precessing by setting any of the following options into the `'bundle-analyzer'` key of your
return app.toTree();
};
```
### Config
You can customize the precessing by setting any of the following configs into the `'bundleAnalyzer'` key of your
`ember-cli-build.js`:
* `ignoreTestFiles` (boolean): by default it will exclude all test files from the output. Set this to `false` to include
them.
- `enabled` (boolean): set to `true` to enable the addon. `false` by default.
* `ignore` (string | string[]): add files to ignore. Glob patterns are supported, e.g. `*-fastboot.js`.
- `ignoreTestFiles` (boolean): by default it will exclude all test files from the output. Set this to `false` to include
them.
- `ignore` (string | string[]): add files to ignore. Glob patterns are supported, e.g. `*-fastboot.js`.
### Source maps
The bundle size output that you see coming from this addon can only be as good as the underlying source maps are. For [source-map-explorer](https://github.com/danvk/source-map-explorer) to correctly process those, they should have the full source code included inline (which is the `sourcesContent` field in a `.map` file).
For the `broccoli-concat` based part of Ember CLI (processing the app itself as well as all v1 addons), enabling source maps using `sourcemaps: { enabled: true },` in `ember-cli-config.js` will be enough.
For any `webpack` based build (be it ember-auto-import or Embroider), the default settings will _not_ be enough. The only setting that works reliably is enabling high-fidelity source maps using `devtool: 'source-map'`.
Again, for enabling source maps with the recommended options, using the `createEmberCLIConfig()` helper as mentioned above is recommended.
For further information consider these resources:
- [Enabling source maps in Ember CLI](https://cli.emberjs.com/release/advanced-use/asset-compilation/#sourcemaps)
- [Adding custom webpack config to ember-auto-import](https://github.com/ef4/ember-auto-import#customizing-build-behavior)
- [Adding custom webpack config to Embroider](https://github.com/embroider-build/embroider#options)
- [webpack's devtool](https://webpack.js.org/configuration/devtool/)
## Usage
You need to have the addon and source maps enabled as described under [Setup](#setup). When following the recommended approach of using `createEmberCLIConfig` to apply the addon provided presets, then opting into the bundle-analyzer enabled mode is done by enabling the `ENABLE_BUNDLE_ANALYZER` environment flag when starting your local dev server. Most likely you will also want to analyze the production mode build, to exclude any debugging code. So the final invocation would be:
```sh
ENABLE_BUNDLE_ANALYZER=true ember serve --prod
```
After startup this addon adds a custom middleware listening to the `/_analyze` URL path. So just open [http://localhost:4200/\_analyze](http://localhost:4200/_analyze) in your web browser to access the analyzer output.
While it processes the data a loading screen might appear, after which the final output should display.
Live reloading is supported, so whenever you change a project file the output will be re-computed and updated automatically.
## Contributing

@@ -70,5 +202,4 @@

## License
This project is licensed under the [MIT License](LICENSE.md).

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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