UNPKG

2.38 kBMarkdownView Raw
1# Custom bundling
2
3Math.js is a large library containing many data types and functions.
4It is well possible that you only need a small portion of the library.
5Math.js allows for creating a custom index file, loading only the data types
6and functions that you need. This give faster load times, and allows bundling
7only the used part of the library with tools like Webpack or browserify.
8
9To load an empty instance of math.js, load `mathjs/core`. This core only
10contains functions `import` and `config`.
11
12```js
13// Load the math.js core
14const core = require('mathjs/core')
15
16// Create a new, empty math.js instance
17// It will only contain methods `import` and `config`
18const math = core.create()
19```
20
21Then, use `math.import` to load the needed data types and functions.
22It's important to load the data types first, and after that load functions
23and constants. The functions are dynamically built, depending on the available
24data types.
25
26```js
27// load the data types you need. Let's say you just want to use fractions,
28// but no matrices, complex numbers, bignumbers, and other stuff.
29//
30// To load all data types:
31//
32// math.import(require('mathjs/lib/type'))
33//
34math.import(require('mathjs/lib/type/fraction'))
35
36// Load the functions you need.
37//
38// To load all functions:
39//
40// math.import(require('mathjs/lib/function'))
41//
42// To load all functions of a specific category:
43//
44// math.import(require('mathjs/lib/function/arithmetic'))
45//
46math.import(require('mathjs/lib/function/arithmetic/add'))
47math.import(require('mathjs/lib/function/arithmetic/subtract'))
48math.import(require('mathjs/lib/function/arithmetic/multiply'))
49math.import(require('mathjs/lib/function/arithmetic/divide'))
50math.import(require('mathjs/lib/function/string/format'))
51```
52
53To see which data types and categories are available, explore the `index.js`
54files in the folder `./lib`.
55
56The imported functions and data types can now be used:
57
58```js
59// Use the loaded functions
60const a = math.fraction(1, 3)
61const b = math.fraction(3, 7)
62const c = math.add(a, b)
63console.log('result:', math.format(c)) // outputs "result: 16/21"
64```
65
66Suppose the custom loading code (loading `mathjs/core` and doing the imports)
67is located in a file `custom_loading.js`. It's now possible to bundle
68this file using for example browserify:
69
70```bash
71$ browserify custom_loading.js -o custom_loading.bundle.js
72```