Single File Components

    This can work very well for small to medium-sized projects, where JavaScript is only used to enhance certain views. In more complex projects however, or when your frontend is entirely driven by JavaScript, these disadvantages become apparent:

    • Global definitions force unique names for every component
    • String templates lack syntax highlighting and require ugly slashes for multiline HTML
    • No CSS support means that while HTML and JavaScript are modularized into components, CSS is conspicuously left out

    All of these are solved by single-file components with a extension, made possible with build tools such as Webpack or Browserify.

    Here’s an example of a file we’ll call Hello.vue:

    Now we get:

    These specific languages are only examples. You could as easily use TypeScript, SCSS, PostCSS, or whatever other preprocessors that help you be productive. If using Webpack with , it also has first-class support for CSS Modules.

    One important thing to note is that separation of concerns is not equal to separation of file types. In modern UI development, we have found that instead of dividing the codebase into three huge layers that interweave with one another, it makes much more sense to divide them into loosely-coupled components and compose them. Inside a component, its template, logic and styles are inherently coupled, and collocating them actually makes the component more cohesive and maintainable.

    Even if you don’t like the idea of Single-File Components, you can still leverage its hot-reloading and pre-compilation features by separating your JavaScript and CSS into separate files:

    Getting Started

    If you want to dive right in and start playing with single-file components, check out this simple todo appSingle File Components - 图6 on CodeSandbox.

    • Node Package Manager (NPM): Read the section about how to get packages from the registry.

    After you’ve taken a day to dive into these resources, we recommend checking out Vue CLISingle File Components - 图9. Follow the instructions and you should have a Vue project with components, ES2015, webpack and hot-reloading in no time!

    The CLI takes care of most of the tooling configurations for you, but also allows fine-grained customization through its own .

    In case you prefer setting up your own build setup from scratch, you will need to manually configure webpack with vue-loaderSingle File Components - 图11. To learn more about webpack itself, check out and webpack learning academySingle File Components - 图13.