'how to filter out files during when ember-cli is building my app (filtering monaco's many files, specifically)

I am trying to reduce monaco-editor dependency size.
I found this answer which shows how to do it on angular - by editing the glob configuration in angular.json file.
What is the corresponding file for this configuration on ember?

EDIT
I found this read me for configuring on ember-cli-build, any idea how to configure?

module.exports = function (defaults) {
  const app = new EmberApp(defaults, {
    autoImport: {
      alias: {
        'monaco-editor': '** what here? **',
      },
    },


Solution 1:[1]

I solved the issue by skipping languages import (which I don't need since I use custom language.
adding the following under webpackConfig:

      new MonacoWebpackPlugin({
        languages: [],
      }),

Here is the full config in ember-cli-build.js:

  return require('@embroider/compat').compatBuild(app, Webpack, {
    staticAddonTestSupportTrees: true,
    staticAddonTrees: true,
    staticHelpers: true,
    // staticComponents: true,
    onOutputPath(outputPath) {
      writeFileSync(join(__dirname, '.embroider-app-path'), outputPath, 'utf8');
    },
    packagerOptions: {
      webpackConfig: {
        module: {
          rules: [
            {
              test: /\.(png|jpg|gif|svg|woff|woff2|eot|ttf|otf|flac)$/i,
              loader: 'file-loader',
              options: {
                name: '[path][name]-[contenthash].[ext]',
              },
            },
          ],
        },
        plugins: [
          new MonacoWebpackPlugin({
            languages: [],
          }),
        ],
      },
    },

});

Solution 2:[2]

I don't know how to read the angular comment there, but what I did was build my own copy of Monaco, with esbuild.

I am trying to reduce monaco-editor dependency size.

generally, if you're using embroider, if you don't import it, it won't be a part of your build.


This is probably more try-hard than you're looking for, but gives you more control over your assets.

here is my package where I do that: https://github.com/NullVoxPopuli/limber/tree/main/packages/monaco

I use this build script:

'use strict';

const path = require('path');
const os = require('os');
const fs = require('fs').promises;
const copy = require('recursive-copy');
const esbuild = require('esbuild');
const { esBuildBrowserTargets } = require('@nullvoxpopuli/limber-consts');

const OUTPUT_DIR = path.join(__dirname, 'dist').toString();

const ME = path.dirname(require.resolve('monaco-editor/package.json'));

const cssLocation = path.join(`${ME}/min/vs/editor`);

const workers = {
  base: path.join(ME, 'esm/vs/editor/editor.main.js'),
  editor: path.join(ME, 'esm/vs/editor/editor.worker.js'),
  json: path.join(ME, 'esm/vs/language/json/json.worker.js'),
  css: path.join(ME, 'esm/vs/language/css/css.worker.js'),
  html: path.join(ME, 'esm/vs/language/html/html.worker.js'),
  ts: path.join(ME, 'esm/vs/language/typescript/ts.worker.js'),
};

/**
 * - Builds Web Workers
 * - Builds a preconfigured bundle with monaco-editor
 * - Copies tall relevant CSS to the same output folder
 */
module.exports = async function build() {
  let buildDir = await fs.mkdtemp(path.join(os.tmpdir(), 'monaco--workers-'));

  await esbuild.build({
    loader: { '.ts': 'ts', '.js': 'js', '.ttf': 'file' },
    entryPoints: [
      workers.editor,
      workers.json,
      workers.css,
      workers.html,
      workers.ts,
      workers.base,
    ],
    bundle: true,
    outdir: buildDir,
    format: 'esm',
    target: esBuildBrowserTargets,
    minify: false,
    sourcemap: false,
  });

  await esbuild.build({
    loader: { '.ts': 'ts', '.js': 'js', '.ttf': 'file' },
    entryPoints: [path.join('preconfigured', 'index.ts')],
    bundle: true,
    outfile: path.join(buildDir, 'preconfigured.js'),
    format: 'esm',
    target: esBuildBrowserTargets,
    // something silly is going on with Monaco and esbuild
    // TODO: report this to ESBuild's GitHub
    minify: false,
    sourcemap: false,
  });

  await copy(`${buildDir}`, OUTPUT_DIR, {
    overwrite: true,
    filter: ['**/*', '!*.nls.*'],
    rename(filePath) {
      if (filePath.includes('ttf')) {
        return 'codicon.ttf';
      }

      return filePath;
    },
  });

  await copy(`${cssLocation}`, OUTPUT_DIR, {
    overwrite: 'inline',
    filter: ['**/*.css'],
  });

  // TODO: how to change the monaco config to allow this to be in a `monaco/` folder
  // const ICON_PATH = 'base/browser/ui/codicons/codicon/codicon.ttf';
  // await copy(path.join(ME, 'esm/vs', ICON_PATH), ICON_PATH)
};

if (require.main === module) {
  module.exports();
}

and then in my ember-cli-build.js here: https://github.com/NullVoxPopuli/limber/blob/main/frontend/ember-cli-build.js#L50 (merging the extraPublic Trees)

I invoke:

  // Desktop Editor
  require('@nullvoxpopuli/limber-monaco/broccoli-funnel')(),

the broccoli-funnel

'use strict';

const path = require('path');
const Funnel = require('broccoli-funnel');

const SRC_FILES = path.join(__dirname, 'dist');

/**
 * This broccoli funnel is for copying the built assets to a target
 * app's public folder. No building occurs
 *
 */
module.exports = function monacoFunnel() {
  return new Funnel(SRC_FILES, {
    destDir: 'monaco/',
  });
};

I then load monaco via a modifier like this:

import { assert } from '@ember/debug';

import type { Args } from './-types';
/**
 * I wish there was a way to specify types-only packages
 * while Limber uses Monaco, it's provided by the limber-monaco
 * broccoli funnel (copied into the public folder).
 *
 * So the devDep on monaco-editor in limber/frontend is *solely*
 * for the type defs
 */
import type * as monaco from 'monaco-editor';

export default function installMonaco(element: HTMLElement, ...[value, updateText, named]: Args) {
  assert(`Expected MONACO to exist`, MONACO);

  element.innerHTML = '';

  let { editor, setText } = MONACO(element, value, updateText, named);

  named.setValue((text) => {
    // changing the text this ways calls updateText for us
    // updateText(text); // update the service / URL
    setText(text); // update the editor
  });

  return () => editor?.dispose();
}

let MONACO:
  | undefined
  | ((
      element: HTMLElement,
      ...args: Args
    ) => { editor: monaco.editor.IStandaloneCodeEditor; setText: (text: string) => void });

export async function setupMonaco() {
  if (MONACO) return;

  // TypeScript doesn't have a way to type files in the public folder
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  MONACO = (await import(/* webpackIgnore: true */ '/monaco/preconfigured.js')).default;
}

and usage:

import monacoModifier from './my-monaco-modifier';

export default class Demo extends Component {
  monaco = monacoModifier
}
<div {{this.monaco}}></div>

You can view this in action here: https://limber.glimdown.com/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dina
Solution 2 NullVoxPopuli