Tree shakeable static methods (using rxjs and lodash in alongside)
Tree shakeable static methods (using rxjs and lodash in alongside)
I want to use rxjs
and lodash
or ramda
in the same project.
I am using typescript with ECMAScript module import statements. (In an ionic project with webpack
as the module bundler)
rxjs
lodash
ramda
webpack
rxjs
and lodash-es
propagate import statements like this, to enable tree shaking:
rxjs
lodash-es
import { map } from 'lodas-es'
import { map } from 'rxjs/operators
As you can see, this approach has two problems:
Name clashes (I could use an alias, but I think this will lead to more confusion)
Very general method names like map
, filter
etc. are in both libraries present and you always have to look in the import statement, which one is meant and where it came from.
map
filter
The static method approach is much more readable in my opinion, because it is so explicit.
I want to keep the syntax like it is in commonjs and also enable tree-shaking. Is this possible somehow? Which alternatives do I have here?
// commonjs
const _ = require('lodash')
const Rx = require('rxjs')
_.filter()
Rx.Observable.from([1,2,3]).pipe(Rx.filter())
// esmodule (this does not work, but I would like to use it this way,
// with tree shaking enabled)
import _ from 'lodash'
import Rx from 'rxjs'
import * as Rx from 'rxjs'
import * as _ from 'lodash'
Rx.map(...)
_.map(...)
I'm pretty sure "god objects" like
_
and Rx
are exactly what prevents tree shaking.– Brandon
2 days ago
_
Rx
Use aliases. It is not confusing if you choose sensible aliases. How about
import {map as _map} from "lodas-es";
and import {map as rxmap} from 'rxjs/operators'
– Brandon
2 days ago
import {map as _map} from "lodas-es";
import {map as rxmap} from 'rxjs/operators'
On the other hand: Importing lodash if you already use RxJS seems counterproductive if your goal is to minimize size.
map
is even built in JavaScript btw.– a better oliver
2 days ago
map
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I am not sure if this prevents tree-shaking, but you can do
import * as Rx from 'rxjs'
andimport * as _ from 'lodash'
, and access functions withRx.map(...)
and_.map(...)
– Sam Herrmann
2 days ago