JavaScript: Dynamic Import with ECMAScript 2020

or how to import static assets at runtime in a VueJS Application

Image for post
Image for post

I am actually creating a small VueJS application for a friend who wants to get a small homepage with content like images and blog entries that can be maintained by himself without my help.

So I decided to create two things configuration files to configure what should been shown and content files.

For blog entries I created a blog.json like this:

"image": "",
"title": "Top western road trips",
"subTitle": "1,000 miles of wonder",
"text": "blog/"
"image": "images/shots/10-500x300.jpg",
"title": "Title",
"subTitle": "Subtitle",
"text": "blog/"

The content is written with Markdown like this for

# Test
Hi this is a test.

### another topic

Everything put into the public folder to avoid Webpack to pack it — I think it is also possible to add another folder that will be copied along.

As far a good, but how can I load those files at runtime to dynamically create the view?

The solution is to use the new feature dynamic import of EcmaScript2020.

In my component I import my json into a local instance during creation.

async created () {
const { default: blog } = await import('../public/assets/blog.json') = blog

The data seems to be nested into a default block, so you have to extract it, here done rest like.

The second time I try to use this mechanism was during loading the Markdown:

const { default: textResponse } = await import(this.blogEntry.text)

But that creates only error message in the console. Trying around gets me to this.

const { default: textResponse } = await import('../../public/blog/')

But for this to work I also have to configure a new loader into Webpack

configureWebpack: {
module: {
rules: [{
test: /\.md$/,
loader: 'raw-loader' // npm install -D raw-loader

That means static string do work, but computed like above do not. So in the end I got back to normal, using fetch:

const textResponse = await fetch(this.blogEntry.text)
const textValue = await textResponse.text()

I hope I could help you a little bit with this explanation and the problems, that arises. If you have a solution to the latter, give me a hint.

See You and happy coding.

Developer since the 80'th, working at Forschungszentrum Jülich ( …

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store