Sávio Raires
Sávio Raires

Reputation: 159

Import module components on demand

I'm using a lib in my project and loading the components of it that I preset through the commonjs module system. The code looks like this:

let echart = require('echarts/lib/echarts');
require('echarts/lib/chart/scatter');
require('echarts/lib/component/title');
require('echarts/lib/component/toolbox');
require('echarts/lib/component/tooltip');
require('echarts/lib/component/legendScroll');

So the bundle generated by the webpack is 1.17 MB in size.

However, I decided to migrate the project to typescript and thus load the components of the lib through the import of es6. The code looks like this:

import * as echarts from 'echarts';
import ECharts = echarts.ECharts;
import EChartOption = echarts.EChartOption;

So the bundle generated by the webpack is 2.21 MB in size. Because loading in this way all components are imported, even the ones I do not use.

Because of this inconvenience I would like to be able to do as in commonjs, someone knows if it is possible and how to do it?

Upvotes: 2

Views: 1095

Answers (1)

unional
unional

Reputation: 15589

You can do the same deep nesting as in CommonJS:

import echarts = require('echarts/lib/echarts')
import 'echarts/lib/chart/scatter'
import 'echarts/lib/component/title'
import 'echarts/lib/component/toolbox'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/legendScroll'

If you use esModuleInterop in TypeScript 2.7, you can do this for the first line:

import echarts from 'echarts/lib/echarts'

Upvotes: 3

Related Questions