Extending the Database (DB)

There will be a lot of resources in the project, and the resources will come with a lot of data, which is managed by the resource database. Extensions can inject resources into the resource database to provide resources like scripts, images, etc. This article will demonstrate how to inject resources into the resource manager via contributions to asset-db.

Registration

Register the Database as follows:

  1. /// package.json
  2. {
  3. "name": "test-package",
  4. "contributions": {
  5. "asset-db": {
  6. "mount": {
  7. "path": "./assets",
  8. "readonly": true
  9. }
  10. }
  11. }
  12. }
  1. interface AssetDBConfig {
  2. mount:{
  3. //Directory of resources, relative to extension
  4. path: string
  5. //Whether the resource is read-only,read and write by default
  6. readonly?: boolean;
  7. }
  8. }

Writing script resources in extensions

We can define the script in the test-package\assets\ resource folder that we just registered, and we’ll start by creating a script foo.ts that

  1. /// foo.ts
  2. import { _decorator, Component, Node } from 'cc';
  3. export const value = 123;
  4. const { ccclass, property } = _decorator;
  5. @ccclass('Foo')
  6. export class Foo extends Component {
  7. start () {
  8. console.log('foo');
  9. }
  10. }

Note: In order to use the cc definitions, we need to copy the definition file of {project directory}\temp\declarations to the extension directory.

Importing extension injected script resources

Earlier we created a new extension test-package that injects the resources under the test-package\assets path into the resource database.

In the project’s script bar.ts we can import the foo.ts script in the following way.

```typescript /// bar.ts import { value, Foo } from ‘db://test-package/foo’;