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