Here's an interesting bit of knowledge: did you know that you can create and interpret relative file URLs like... actual URLs?
All content covered in this post will only work with ESM
Now, it might be hard to find a practical use for this, but it is undoubtedly very cool 😎. Enough talk; let's look at some code.
// In your first file:
import './example.js?abc=123';
// In your second file, example.js:
const url = new URL(import.meta.url);
const searchParam = url.searchParams.get('abc');
console.log(searchParam); // → '123'
Here, import.meta.url
is used to display the full URL used to import the module. In this case, for example, it might be:
file:///C:/Some/Folder/Path/example.js?abc=123
From here, we can create an instance of a URL
, which will make it super easy to parse search parameters.
How could this be used?
I have no idea 😂! Maybe it could be used as a shortcut for very primitive module configuration? For example, using the very popular utility package dotenv
.
Works with dotenv-vault. Learn more at dotenv.org.
dotenv
Dotenv is a zero-dependency module that loads environment variables from a .env
file into process.env
. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology.
Install
# install locally (recommended)
npm install dotenv --save
Or installing with yarn? yarn add dotenv
Usage
Create a .env
file in the root of your project:
S3_BUCKET="YOURS3BUCKET"
SECRET_KEY="YOURSECRETKEYGOESHERE"
As early as possible in your application, import and configure dotenv:
require('dotenv').config()
console.log(process.env) // remove this after you've confirmed it working
.. or using ES6?
import 'dotenv/config' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
import express from 'express'
That's it. process.env
now has the keys and values you defined in your .env
file:
require('dotenv').config()
.
…Instead of:
import dotenv from 'dotenv';
dotenv.config({ debug: true });
You could do this! 🦄
import 'dotenv/config?debug=true';
I'd love to know your thoughts 😆
Discussion (2)
I use it in my test harness to create a named test suite by a single import line. Instead of the usual importing
index.min.mjs
and calling the test suite factory:I can import
suite.min.mjs
which recognises the URL parametername
, creates a test suite with the name and exports it:It's a pity that this works only in browsers. Node.js doesn't separate the URL parameters from the file path, which leads to an invalid script path, if they are attached:
This has probably a consequence that the URL parameters can't be used in subpackages either. If a library exposes a subpackage
suite
, for example:it has to be used as-is:
instead of the desired:
which fails:
Related:
WOW! I never thought of that use case, and your findings are really interesting! Thank you so much!! ♥️♥️