Skip to content

Commit

Permalink
ViteJs - ES6 Module
Browse files Browse the repository at this point in the history
  • Loading branch information
mtvbrianking committed May 1, 2023
1 parent 0b2d9ca commit fea4753
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 2 deletions.
17 changes: 15 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,29 @@ You should `.gitignore` the above auto-generated `routes.json` file.

### Publish resources

Publish JavaScript router to `resources/js/router.js`
Publish JavaScript router to `resources/js`

```bash
php artisan vendor:publish --provider="Bmatovu\JsRoutes\JsRoutesServiceProvider"
```

Load JavaScript router; usually from `resources/js/bootstrap.js`
**Using Webpack | Laravel Mix**

Load JavaScript router; usually in `resources/js/app.js`

```js
window.route = require('./router.js').route;

console.log(route('login'));
```

**Using ViteJS**

```js
import { route } from './router.mjs';
window.route = route;

console.log(route('login'));
```

### Compile JS routes
Expand Down
57 changes: 57 additions & 0 deletions resources/js/router.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import routes from './routes.json' assert {type: 'json'};

var appUrl = document.head.querySelector('meta[name="app-url"]').content;

if (!String.prototype.endsWith) {
String.prototype.endsWith = function (search, this_len) {
if (this_len === undefined || this_len > this.length) {
this_len = this.length;
}
return this.substring(this_len - search.length, this_len) === search;
};
}

export function route(name, params) {
if (routes[name] === undefined) {
console.error('Unknown route ', name);
return false;
}

if (params === null || typeof params !== 'object') {
return appUrl + '/' + routes[name];
}

var path = routes[name]
.split('/')
.map(function (part) {
if (part === null) {
return '';
}

if (part[0] != '{') {
return part;
}

var param = part.match(/[^{\}]+/g)[0];

if (param.endsWith('?')) {
param = param.slice(0, -1);
}

var value = params['' + param];

delete params['' + param];

return value;
})
.join('/')
.replace(/\/+$/g, '');

var query = Object.keys(params)
.map(function (key) {
return key + '=' + params[key];
})
.join('&');

return query ? appUrl + '/' + path + '?' + encodeURI(query) : appUrl + '/' + path;
}

0 comments on commit fea4753

Please sign in to comment.