Consuming Dexie as a module
Short Version
Save the above code to for example mydatabase.js
and import it from another module:
Long Version
Dexie is written in Typescript/ES6 and distributed in both the UMD and ES formats. It can be consumed either as a plain script tag, required as a CJS, AMD or imported as an ES module.
Vanilla scripts are nice when testing out something. But a module-based approach is better in the long term and package manager helps you keep track of your dependencies. There are lots of combinations of package- and module systems to choose from. For web apps, npm + webpack
works perfectly well so let's start with that alternative.
NPM and webpack
With NPM you keep track of versions and dependencies for your app. It's also a perfect platform to use when using commonjs modules and webpack.
Assuming you've already installed nodejs that bundles npm
with it. Start by initing your new npm package. CD to a brand new dir and do:
Write your javascript file (index.js or whatever) that uses dexie:
index.js
This script uses Dexie.spawn() and yield. You need a modern browser to open it. Note that Dexie does not require using the yield keyword, but it simplifies your code a lot if you do. Read more about this on Simplify with yield.
Now, create a HTML page:
index.html
As you can see, the page just includes a file called bundle.js. That is the file that webpack will generate when doing the following command:
Now your done to open your web page in a browser. If you're on the Edge browser, you cant just open the page from your file system because it would block indexedDB. You could use the nice module http-server to start a local web server and access it from there.
Now start a browser towards http://localhost:8080/ and press F12 to view the console log output.
Done.
NPM and rollup
main.js:
index.html
Shell:
The es6 version is located on https://npmcdn.com/dexie@latest/src/Dexie.js but rollup will read the jsnext:main attribute in package.json, so it's enough to just import 'dexie'.
requirejs
requirejs doesn't find modules with the magic that goes with npm and webpack. So you have to update your require config accordingly:
systemjs
System.js is also not that magic as npm and webpack. You need to configure both its location and its module type. Here's how to do that:
systemjs.config.js
Typescript
With typescript and npm, it's super-easy. Just make sure to:
Use npm to install dexie
npm install dexie --save
Make sure tsconfig has
{ moduleResolution: 'node' }
In your code, import dexie and subclass it:
That's it! Typings are delivered with the package. DON'T:use tsd or typings to add dexie's type definitions. They are bundled with the lib and pointed out via package.json's typings
property.
See also Dexie Typescript Tutorial
Next steps
Architectural Overview
or
Look at some samples
or
Migrating existing DB to Dexie
or
Back to Tutorial