Consuming Dexie as a module
Short Version
import Dexie from 'dexie';
const db = new Dexie('myDb');
db.version(1).stores({
friends: `name, age`
});
export default db;
Save the above code to for example mydatabase.js
and import it from another module:
import db from './mydatabase';
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:
mkdir hello-dexie
cd hello-dexie
npm init --yes
npm install dexie --save
npm install webpack -g
Write your javascript file (index.js or whatever) that uses dexie:
index.js
import Dexie from 'dexie';
var db = new Dexie('hellodb');
db.version(1).stores({
tasks: '++id,date,description,done'
});
async function test() {
var id = await db.tasks.put({date: Date.now(), description: 'Test Dexie', done: 0});
console.log("Got id " + id);
// Now lets add a bunch of tasks
await db.tasks.bulkPut([
{date: Date.now(), description: 'Test Dexie bulkPut()', done: 1},
{date: Date.now(), description: 'Finish testing Dexie bulkPut()', done: 1}
]);
// Ok, so let's query it
var tasks = await db.tasks.where('done').above(0).toArray();
console.log("Completed tasks: " + JSON.stringify(tasks, 0, 2));
// Ok, so let's complete the 'Test Dexie' task.
await db.tasks
.where('description')
.startsWithIgnoreCase('test dexi')
.modify({done: 1});
console.log ("All tasks should be completed now.");
console.log ("Now let's delete all old tasks:");
// And let's remove all old tasks:
await db.tasks
.where('date')
.below(Date.now())
.delete();
console.log ("Done.");
}
test().catch (err => {
console.error ("Uh oh! " + err.stack);
});
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
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script type="text/javascript" src="bundle.js" charset="utf-8"></script>
</body>
</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:
webpack ./index.js bundle.js
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.
npm install -g http-server
http-server .
Now start a browser towards http://localhost:8080/ and press F12 to view the console log output.
Done.
NPM and rollup
main.js:
import Dexie from 'dexie';
var db = new Dexie('mydb');
db.version(1).stores({foo: 'id'});
db.foo.put({id: 1, bar: 'hello rollup'}).then(id => {
return db.foo.get(id);
}).then (item => {
alert ("Found: " + item.bar);
}).catch (err => {
alert ("Error: " + (err.stack || err));
});
index.html
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script type="text/javascript" src="bundle.js" charset="utf-8"></script>
</body>
</html>
Shell:
npm install dexie --save
npm install rollup -g
rollup main.js -o bundle.js
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:
require.config({
paths: {
"dexie": "node_modules/dexie/dist/dexie" // or the bower location, or simply https://npmcdn.com/dexie/dist/dexie
}
});
// And to consume it:
requirejs(['dexie'], function (Dexie) {
var db = new Dexie('dbname');
...
});
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:
npm install dexie --save
systemjs.config.js
System.config({
map: {
'dexie': 'node_modules/dexie/dist/dexie.js'
},
packages: {
'dexie': { format: 'amd' } // or 'cjs'
}
});
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:
// Import Dexie
import Dexie from 'dexie';
// Subclass it
class MyDatabase extends Dexie {
contacts: Dexie.Table<IContact, number>;
constructor (databaseName) {
super(databaseName);
this.version(1).stores({
contacts: '++id,first,last'
});
this.contacts = this.table('contacts'); // Just informing Typescript what Dexie has already done...
}
}
interface IContact {
id?: number,
first: string,
last: string
}
// Instantiate it
var db = new MyDatabase('myDb');
// Open it
db.open().catch(err => {
console.error(`Open failed: ${err.stack}`);
});
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
Table of Contents
- API Reference
- Access Control in Dexie Cloud
- Add demo users
- Add public data
- Authentication in Dexie Cloud
- Best Practices
- Building Addons
- Collection
- Collection.and()
- Collection.clone()
- Collection.count()
- Collection.delete()
- Collection.desc()
- Collection.distinct()
- Collection.each()
- Collection.eachKey()
- Collection.eachPrimaryKey()
- Collection.eachUniqueKey()
- Collection.filter()
- Collection.first()
- Collection.keys()
- Collection.last()
- Collection.limit()
- Collection.modify()
- Collection.offset()
- Collection.or()
- Collection.primaryKeys()
- Collection.raw()
- Collection.reverse()
- Collection.sortBy()
- Collection.toArray()
- Collection.uniqueKeys()
- Collection.until()
- Compound Index
- Consistency in Dexie Cloud
- Consistent add() operator
- Consistent remove() operator
- Consistent replacePrefix() operator
- Consuming Dexie as a module
- Custom Emails in Dexie Cloud
- DBCore
- DBCoreAddRequest
- DBCoreCountRequest
- DBCoreCursor
- DBCoreDeleteRangeRequest
- DBCoreDeleteRequest
- DBCoreGetManyRequest
- DBCoreGetRequest
- DBCoreIndex
- DBCoreKeyRange
- DBCoreMutateRequest
- DBCoreMutateResponse
- DBCoreOpenCursorRequest
- DBCorePutRequest
- DBCoreQuery
- DBCoreQueryRequest
- DBCoreQueryResponse
- DBCoreRangeType
- DBCoreSchema
- DBCoreTable
- DBCoreTableSchema
- DBCoreTransaction
- DBCoreTransactionMode
- DBPermissionSet
- Deprecations
- Derived Work
- Design
- Dexie Cloud API
- Dexie Cloud API Limits
- Dexie Cloud Best Practices
- Dexie Cloud CLI
- Dexie Cloud Docs
- Dexie Cloud REST API
- Dexie Cloud Web Hooks
- Dexie Constructor
- Dexie.AbortError
- Dexie.BulkError
- Dexie.ConstraintError
- Dexie.DataCloneError
- Dexie.DataError
- Dexie.DatabaseClosedError
- Dexie.IncompatiblePromiseError
- Dexie.InternalError
- Dexie.InvalidAccessError
- Dexie.InvalidArgumentError
- Dexie.InvalidStateError
- Dexie.InvalidTableError
- Dexie.MissingAPIError
- Dexie.ModifyError
- Dexie.NoSuchDatabaseErrorError
- Dexie.NotFoundError
- Dexie.Observable
- Dexie.Observable.DatabaseChange
- Dexie.OpenFailedError
- Dexie.PrematureCommitError
- Dexie.QuotaExceededError
- Dexie.ReadOnlyError
- Dexie.SchemaError
- Dexie.SubTransactionError
- Dexie.Syncable
- Dexie.Syncable.IDatabaseChange
- Dexie.Syncable.IPersistentContext
- Dexie.Syncable.ISyncProtocol
- Dexie.Syncable.StatusTexts
- Dexie.Syncable.Statuses
- Dexie.Syncable.registerSyncProtocol()
- Dexie.TimeoutError
- Dexie.TransactionInactiveError
- Dexie.UnknownError
- Dexie.UnsupportedError
- Dexie.UpgradeError()
- Dexie.VersionChangeError
- Dexie.VersionError
- Dexie.[table]
- Dexie.addons
- Dexie.async()
- Dexie.backendDB()
- Dexie.close()
- Dexie.currentTransaction
- Dexie.debug
- Dexie.deepClone()
- Dexie.defineClass()
- Dexie.delByKeyPath()
- Dexie.delete()
- Dexie.derive()
- Dexie.events()
- Dexie.exists()
- Dexie.extend()
- Dexie.fakeAutoComplete()
- Dexie.getByKeyPath()
- Dexie.getDatabaseNames()
- Dexie.hasFailed()
- Dexie.ignoreTransaction()
- Dexie.isOpen()
- Dexie.js
- Dexie.name
- Dexie.on()
- Dexie.on.blocked
- Dexie.on.close
- Dexie.on.error
- Dexie.on.populate
- Dexie.on.populate-(old-version)
- Dexie.on.ready
- Dexie.on.storagemutated
- Dexie.on.versionchange
- Dexie.open()
- Dexie.override()
- Dexie.semVer
- Dexie.setByKeyPath()
- Dexie.shallowClone()
- Dexie.spawn()
- Dexie.table()
- Dexie.tables
- Dexie.transaction()
- Dexie.transaction()-(old-version)
- Dexie.use()
- Dexie.verno
- Dexie.version
- Dexie.version()
- Dexie.vip()
- Dexie.waitFor()
- DexieCloudOptions
- DexieError
- Docs Home
- Download
- EntityTable
- Export and Import Database
- Get started with Dexie in Angular
- Get started with Dexie in React
- Get started with Dexie in Svelte
- Get started with Dexie in Vue
- Hello World
- How To Use the StorageManager API
- Inbound
- IndexSpec
- Indexable Type
- IndexedDB on Safari
- Invite
- Member
- Migrating existing DB to Dexie
- MultiEntry Index
- PersistedSyncState
- Privacy Policy
- Promise
- Promise.PSD
- Promise.catch()
- Promise.finally()
- Promise.on.error
- Promise.onuncatched
- Questions and Answers
- Realm
- Releasing Dexie
- Road Map
- Road Map: Dexie 5.0
- Road Map: Dexie Cloud
- Role
- Run Dexie Cloud on Own Servers
- Sharding and Scalability
- Simplify with yield
- Support Ukraine
- SyncState
- Table
- Table Schema
- Table.add()
- Table.bulkAdd()
- Table.bulkDelete()
- Table.bulkGet()
- Table.bulkPut()
- Table.bulkUpdate()
- Table.clear()
- Table.count()
- Table.defineClass()
- Table.delete()
- Table.each()
- Table.filter()
- Table.get()
- Table.hook('creating')
- Table.hook('deleting')
- Table.hook('reading')
- Table.hook('updating')
- Table.limit()
- Table.mapToClass()
- Table.name
- Table.offset()
- Table.orderBy()
- Table.put()
- Table.reverse()
- Table.schema
- Table.toArray()
- Table.toCollection()
- Table.update()
- Table.where()
- The main limitations of IndexedDB
- Transaction
- Transaction.abort()
- Transaction.on.abort
- Transaction.on.complete
- Transaction.on.error
- Transaction.table()
- Tutorial
- Typescript
- Typescript (old)
- Understanding the basics
- UserLogin
- Version
- Version.stores()
- Version.upgrade()
- WhereClause
- WhereClause.above()
- WhereClause.aboveOrEqual()
- WhereClause.anyOf()
- WhereClause.anyOfIgnoreCase()
- WhereClause.below()
- WhereClause.belowOrEqual()
- WhereClause.between()
- WhereClause.equals()
- WhereClause.equalsIgnoreCase()
- WhereClause.inAnyRange()
- WhereClause.noneOf()
- WhereClause.notEqual()
- WhereClause.startsWith()
- WhereClause.startsWithAnyOf()
- WhereClause.startsWithAnyOfIgnoreCase()
- WhereClause.startsWithIgnoreCase()
- db.cloud.configure()
- db.cloud.currentUser
- db.cloud.currentUserId
- db.cloud.events.syncComplete
- db.cloud.invites
- db.cloud.login()
- db.cloud.logout()
- db.cloud.options
- db.cloud.permissions()
- db.cloud.persistedSyncState
- db.cloud.roles
- db.cloud.schema
- db.cloud.sync()
- db.cloud.syncState
- db.cloud.userInteraction
- db.cloud.usingServiceWorker
- db.cloud.version
- db.cloud.webSocketStatus
- db.members
- db.realms
- db.roles
- db.syncable.connect()
- db.syncable.delete()
- db.syncable.disconnect()
- db.syncable.getOptions()
- db.syncable.getStatus()
- db.syncable.list()
- db.syncable.on('statusChanged')
- db.syncable.setFilter()
- dexie-cloud-addon
- dexie-react-hooks
- liveQuery()
- unhandledrejection-event
- useLiveQuery()
- useObservable()
- usePermissions()