DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • React, Angular, and Vue.js: What’s the Technical Difference?
  • Leveraging Salesforce Using a Client Written In Vue.js
  • The Import Statement With an Emscripten-Generated WebAssembly Module in Vue.js
  • Validation Forms in Vue.js Apps Using Vuelidate library

Trending

  • Segmentation Violation and How Rust Helps Overcome It
  • Building Scalable and Resilient Data Pipelines With Apache Airflow
  • Enhancing Avro With Semantic Metadata Using Logical Types
  • Understanding Java Signals
  1. DZone
  2. Coding
  3. JavaScript
  4. Vue.js Single-File JavaScript Components in the Browser

Vue.js Single-File JavaScript Components in the Browser

Browser support for native JavaScript modules is finally happening. In this article, we show you what this means for Vue.js developers.

By 
Anthony Gore user avatar
Anthony Gore
DZone Core CORE ·
Updated Feb. 04, 20 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
22.5K Views

Join the DZone community and get the full member experience.

Join For Free

Browser support for native JavaScript modules is finally happening. The latest versions of Safari and Chrome support them, Firefox and Edge will soon too.

One of the cool things about JavaScript modules for Vue.js users is that they allow you to organize your components into their own files without any kind of build step required.

In this article, I'm going to show you how to write a single-file component as a JavaScript module and use it in a Vue.js app. You can do this all in the browser without any Babel or Webpack!

When I say "single-file component" I'm talking about a single JavaScript file which exports a complete component definition. I'm not talking about the single .vue file you're used to. Sorry if you're disappointed. But I still think this is pretty cool, so check it out.

Project Setup

Let's use the vue-cli simple template to do this. That's right, the one without any Webpack.

Shell
 




xxxxxxxxxx
1


 
1
$ vue init simple sfc-simple


The complete code for this tutorial is in this GitHub repo if you want to download it.

Change into the directory and create the files we'll need:

Shell
 




xxxxxxxxxx
1


 
1
$ cd sfc-simple
2
$ touch app.js
3
$ touch SingleFileComponent.js



Remove the inline script from index.html and instead use script tags to link to our modules. Note the type="module" attribute:

HTML
 




xxxxxxxxxx
1
12


 
1
<!DOCTYPE html>
2
<html>
3
<head>
4
  <title>Vue.js Single-File JavaScript Component Demo</title>
5
  <script src="https://unpkg.com/vue"></script>
6
</head>
7
<body>
8
  <div id="app"></div>
9
  <script type="module" src="SingleFileComponent.js"></script>
10
  <script type="module" src="app.js"></script>
11
</body>
12
</html>



Creating a Single-File JavaScript Component

This is a component like any other you've created, only you export the configuration object since it's a module:

SingleFileComponent.js

JavaScript
 




xxxxxxxxxx
1
13


 
1
export default {
2
  template: `
3
    <div>
4
     <h1>Single-file JavaScript Component</h1>
5
     <p>{{ message }}</p>
6
    </div>
7
  `,
8
  data() {
9
    return {
10
      message: 'Oh hai from the component'
11
    }
12
  }
13
}



Now we can import it and use it in our Vue app:

app.js

JavaScript
 




xxxxxxxxxx
1


 
1
import SingleFileComponent from 'SingleFileComponent.js';
2
 
          
3
new Vue({
4
  el: '#app',
5
  components: {
6
    SingleFileComponent
7
  }
8
});



index.html

HTML
 




xxxxxxxxxx
1


 
1
<div id="app">
2
  <single-file-component></single-file-component>
3
</div>


Serving the App

For a simple project like this all you need is a static server on the command line with the http-server module:

Shell
 




xxxxxxxxxx
1


 
1
# This will serve the project directory at localhost:8080
2
$ http-server



To view the app you will, of course, need to use a browser which supports JavaScript modules. I'm using Chrome 61.

Single file component

Single file component


Fallback

What if the user's browser doesn't support JavaScript modules? This will be the case for most users, for a while.

We can use a script tag with the nomodule attribute to write a simple error message to the document:

HTML
 




xxxxxxxxxx
1
11


 
1
 
          
2
<body>
3
  <div id="app">
4
    <single-file-component></single-file-component>
5
  </div>
6
  <script type="module" src="SingleFileComponent.js"></script>
7
  <script type="module" src="app.js"></script>
8
  <script nomodule>
9
    document.getElementById("app").innerHTML = "Your browser doesn't support JavaScript modules :(";
10
  </script>
11
</body>



A far better fallback, though, would be to use a Webpack bundled version of the project. This simple config will do the job:

JavaScript
 




xxxxxxxxxx
1
20


 
1
var path = require('path')
2
var webpack = require('webpack')
3
 
          
4
module.exports = {
5
  entry: './app.js',
6
  output: {
7
    path: path.resolve(__dirname, './dist'),
8
    publicPath: '/dist/',
9
    filename: 'build.js'
10
  },
11
  module: {
12
    rules: [
13
      {
14
        test: /\.js$/,
15
        loader: 'babel-loader',
16
        exclude: /node_modules/
17
      }
18
    ]
19
  }
20
}



After a build, the bundle can now be loaded as the fallback script:

HTML
 




xxxxxxxxxx
1


 
1
<body>
2
  ...
3
  <script type="module" src="SingleFileComponent.js"></script>
4
  <script type="module" src="app.js"></script>
5
  <script nomodule src="/dist/build.js"></script>
6
</body>



This Webpack version will work identically in a browser without native module support. Here it is in Firefox, note that build.js has loaded and not the module:

Loading component from build

Loading component from build


Performance Comparison

Since we've now got two versions of the app available, one using the native JavaScript module system, and the other using Webpack, what performance difference is there?

JavaScript modules vs Webpack

JavaScript modules vs Webpack


Using the module system gives you a smaller project size. However, the Webpack project loads quicker overall.

Note: these figures are from a Lighthouse test with an HTTP/2 server.

I suspect preloading would improve the speed of the modules project, but we're a bit early for this to work:

Vue Twitter conversation

Webpack is still the better choice for module-based architectures, but it's nice to know native modules are a thing.


JavaScript Vue.js

Published at DZone with permission of Anthony Gore, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • React, Angular, and Vue.js: What’s the Technical Difference?
  • Leveraging Salesforce Using a Client Written In Vue.js
  • The Import Statement With an Emscripten-Generated WebAssembly Module in Vue.js
  • Validation Forms in Vue.js Apps Using Vuelidate library

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!