Per questo articolo sarà utile una comprensione dei componenti a file singolo (SFC) e Node Package Manager (NPM) di Vue.
L'interfaccia della riga di comando di un framework, o CLI, è il metodo preferito per impalcare un progetto. Fornisce un punto di partenza di file, cartelle e configurazione. Questo scaffolding fornisce anche un processo di sviluppo e creazione. Un processo di sviluppo fornisce un modo per vedere gli aggiornamenti che si verificano durante la modifica del progetto. Il processo di compilazione crea la versione finale dei file da utilizzare in produzione.
L'installazione e l'esecuzione di Vue.js ("Vue") può essere eseguita con un tag script che punta alla rete di distribuzione dei contenuti (CDN) di Vue. Non è necessario alcun processo di creazione o sviluppo. Tuttavia, se si utilizzano componenti Vue a file singolo (SFC), è necessario convertire quei file in qualcosa che il browser possa capire. I file devono essere convertiti in HTML (Hyper-Text Markup Language), CSS (Cascading Style Sheets) e JavaScript (JS). In questo caso, è necessario utilizzare un processo di sviluppo e creazione.
Invece di fare affidamento sulla CLI di Vue per impalcare il nostro progetto e fornirci un processo di sviluppo e creazione, costruiremo un progetto da zero. Creeremo il nostro processo di sviluppo e creazione utilizzando Webpack.
Cos'è Webpack?
Webpack è un bundler di moduli. Unisce il codice di più file in uno solo. Prima di Webpack, l'utente includeva un tag script per ogni file JavaScript. Sebbene i browser supportino lentamente i moduli ES6, Webpack continua ad essere il modo preferito per creare codice modulare.
Oltre ad essere un bundler di moduli, Webpack può anche trasformare il codice. Ad esempio, Webpack può prendere JavaScript moderno (ECMAScript 6+) e convertirlo in ECMAScript 5. Mentre Webpack raggruppa il codice stesso, trasforma il codice con caricatori e plug-in. Pensa a caricatori e plugin come componenti aggiuntivi per Webpack.
Webpack e Vue
I componenti a file singolo ci consentono di costruire un intero componente (struttura, stile e funzione) in un unico file. Inoltre, la maggior parte degli editor di codice fornisce l'evidenziazione della sintassi e il linting per questi SFC.

Notare che il file termina con .vue. Il browser non sa cosa fare con quell'estensione. Webpack, tramite l'uso di caricatori e plug-in, trasforma questo file in HTML, CSS e JS che il browser può utilizzare.
Il progetto: creare un'applicazione Hello World Vue utilizzando componenti a file singolo.
Passaggio 1: creare la struttura del progetto
Il progetto Vue più semplice includerà un file HTML, JavaScript e un file Vue (il file che termina con .vue ). Metteremo questi file in una cartella chiamata src
. La cartella dei sorgenti ci aiuterà a separare il codice che stiamo scrivendo dal codice che Webpack creerà alla fine.
Dato che useremo Webpack, abbiamo bisogno di un file di configurazione Webpack.
Inoltre, useremo un compilatore chiamato Babel. Babel ci permette di scrivere codice ES6 che poi compila in ES5. Babel è una di quelle "funzionalità aggiuntive" per Webpack. Babel ha bisogno anche di un file di configurazione.
Infine, poiché utilizziamo NPM, avremo anche una cartella node_modules e un file package.json. Questi verranno creati automaticamente quando inizializziamo il nostro progetto come progetto NPM e iniziamo a installare le nostre dipendenze.
Per iniziare, crea una cartella chiamata hello-world
. Dalla riga di comando, passa a quella directory ed esegui npm init
. Segui le istruzioni sullo schermo per creare il progetto. Quindi, crea il resto delle cartelle (ad eccezione di node_modules
) come descritto sopra. La struttura del tuo progetto dovrebbe assomigliare a questa:

Passaggio 2: installa le dipendenze
Ecco una rapida carrellata delle dipendenze che stiamo utilizzando:
vue : il framework JavaScript
vue-loader e vue-template-compiler : utilizzati per convertire i nostri file Vue in JavaScript.
webpack : lo strumento che ci permetterà di passare il nostro codice attraverso alcune trasformazioni e raggrupparlo in un unico file.
webpack-cli: necessario per eseguire i comandi Webpack.
webpack-dev-server : sebbene non sia necessario per il nostro piccolo progetto (poiché non faremo richieste HTTP), continueremo a "servire" il nostro progetto da un server di sviluppo.
babel-loader : trasforma il nostro codice ES6 in ES5. (Ha bisogno di aiuto dalle prossime due dipendenze.)
@ babel / core e @ babel / preset-env : Babel da solo non fa nulla al tuo codice. Questi due "add-on" ci permetteranno di trasformare il nostro codice ES6 in codice ES5.
css-loader: prende il CSS che scriviamo nel nostro file.vue
file o qualsiasi CSS che potremmo importare in uno qualsiasi dei nostri file JavaScript e risolvere il percorso di tali file. In altre parole, scopri dove si trova il CSS. Questo è un altro caricatore che da solo non farà molto. Abbiamo bisogno del prossimo caricatore per fare effettivamente qualcosa con il CSS.
vue-style-loader : prendi il CSS che abbiamo ottenuto da nostro css-loader
e inseriscilo nel nostro file HTML. Questo creerà e inietterà un tag di stile nell'intestazione del nostro documento HTML.
html-webpack-plugin : prendi il nostro index.html e inserisci il nostro file JavaScript in bundle nella testa. Quindi, copia questo file nel filedist
cartella.
rimraf : Ci permette, dalla riga di comando, di eliminare i file. Questo tornerà utile quando costruiremo il nostro progetto più volte. Lo useremo per eliminare tutte le vecchie build.
Installiamo ora queste dipendenze. Dalla riga di comando, esegui:
npm install vue vue-loader vue-template-compiler webpack webpack-cli webpack-dev-server babel-loader @babel/core @babel/preset-env css-loader vue-style-loader html-webpack-plugin rimraf -D
Nota: la "-D" alla fine contrassegna ogni dipendenza come dipendenza di sviluppo nel nostro package.json. Stiamo raggruppando tutte le dipendenze in un file, quindi, per il nostro piccolo progetto, non abbiamo dipendenze di produzione.
Passaggio 3: creare i file (ad eccezione del nostro file di configurazione Webpack).
{{ message }} export default { data() { return { message: 'Hello World', }; }, }; #app { font-size: 18px; font-family: 'Roboto', sans-serif; color: blue; }
Vue Hello World
import Vue from 'vue'; import App from './App.vue'; new Vue({ el: '#app', render: h => h(App), });
module.exports = { presets: ['@babel/preset-env'], }
Fino a questo punto, niente dovrebbe sembrare troppo estraneo. Ho mantenuto ogni file molto semplice. Ho aggiunto solo CSS e JS minimi per vedere il nostro flusso di lavoro in azione.
Passaggio 4: istruire Webpack su cosa fare
Tutta la configurazione a cui Webpack deve accedere è ora presente. Dobbiamo fare due cose finali: dire a Webpack cosa fare ed eseguire Webpack.
Di seguito è riportato il file di configurazione Webpack ( webpack.config.js
). Crea questo file nella directory principale del progetto. Riga per riga discuteremo di ciò che sta accadendo.
const HtmlWebpackPlugin = require('html-webpack-plugin'); const VueLoaderPlugin = require('vue-loader/lib/plugin'); module.exports = { entry: './src/main.js', module: { rules: [ { test: /\.js$/, use: 'babel-loader' }, { test: /\.vue$/, use: 'vue-loader' }, { test: /\.css$/, use: ['vue-style-loader', 'css-loader']}, ] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html', }), new VueLoaderPlugin(), ] };
Righe 1 e 2: stiamo importando i due plugin che utilizziamo di seguito. Nota, i nostri caricatori normalmente non devono essere importati, ma solo i nostri plugin. E nel nostro caso, il filevue-loader
(che usiamo nella riga 9) necessita anche di un plugin per funzionare (tuttavia, Babel, ad esempio, non lo fa).
Riga 4: esportiamo la nostra configurazione come oggetto. Questo ci dà accesso quando eseguiamo i comandi Webpack.
Riga 5: questo è il nostro modulo di accesso. Webpack ha bisogno di un punto di partenza. Guarda nel nostro main.js
file e poi inizia a setacciare il nostro codice da quel punto.
Righe 6 e 7: questo è l'oggetto modulo. In questo caso, passiamo principalmente una serie di regole. Ogni regola dice a Webpack come gestire determinati file. Quindi, mentre Webpack utilizza il punto di ingresso di main.js
per iniziare a setacciare il nostro codice, utilizza le regole per trasformare il nostro codice.
Riga 8 (regola): questa regola indica a Webpack di utilizzare babel-loader
su tutti i file che terminano con .js
. Ricorda, Babel trasformerà ES6 + in ES5.
Riga 9 (regola): questa regola indica a Webpack di utilizzarevue-loader
(and don’t forget the associated plugin on line 17) to transform our .vue
files into JavaScript.
Line 10 (rule): Sometimes we want to pass a file through two loaders. Counterintuitively, Webpack will pass the file from right to left instead of left to right. Here we are using two loaders and saying to Webpack: “get my CSS from my Vue file or any JavaScript files(css-loader
) and inject it into my HTML as a style tag (vue-style-loader
).
Lines 11 and 12: Close out our rules array and module object.
Lines 13: Create a plugins array. Here we will add the two plugins we need.
Line: 14 -16 (plugin): The HtmlWebpackPlugin
takes the location of our index.html file and adds our bundled JavaScript file to it via a script tag. This plugin will also copy the HTML file to our distribution folder when we build our project.
Line 17 (plugin): The VueLoaderPlugin
works with our vue-loader
to parse our .vue
files.
Line 18: Close out the plugins array.
Line 19: Close out the Webpack object that we are exporting.
Step 5: Setting up our package.json file so we can run Webpack
Our configuration is complete, now we want to see our application. Ideally, as we make changes to our application, the browser would update automatically. This is possible with webpack-dev-server
.
Delete the test
script in our package.json
file, and replace it with a script to serve our application:
{ "name": "hello-world", "version": "1.0.0", "description": "", "main": "main.js", "scripts": { "serve": "webpack-dev-server --mode development" }, "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.1.6", "@babel/preset-env": "^7.1.6", "babel-loader": "^8.0.4", "css-loader": "^1.0.1", "html-webpack-plugin": "^3.2.0", "rimraf": "^2.6.2", "vue": "^2.5.17", "vue-loader": "^15.4.2", "vue-style-loader": "^4.1.2", "vue-template-compiler": "^2.5.17", "webpack": "^4.26.0", "webpack-cli": "^3.1.2", "webpack-dev-server": "^3.1.10" }, "dependencies": {} }
The name of this command is your choice. I chose to call mine serve
since we will be serving our application.
From our terminal or command line, we can run npm run serve
and that in turn will run webpack-dev-server --mode development
.
The --mode development
is what’s called a flag or option. We haven’t talked about this, but it essentially instructs Webpack that you are in development mode. We can also pass in --mode production
which we will do when we build our project. These aren’t necessarily required for Webpack to work. Without these, you will get a warning message telling you to provide a mode when you run Webpack .
I say “necessarily required” because Webpack will minimize our code in production mode but not in development. So, don’t think those commands don’t do anything–they do.
Let’s run npm run serve
and see what happens.
When we run npm run serve
we get some output in our terminal. And, if everything goes well:

And if we scroll up a bit:

Point your browser to //localhost:8080
. You will see your Blue Hello World message in Roboto font.

Now, let’s update the project and change the message to Hello Universe
. Notice that the webpage refreshes automatically. That’s great, right? Can you think of a downside?
Let’s change the application just a bit and include an input which we will bind a variable to (with v-model
). We will output the variable in an
tag below the input. I’ve also updated the styling section to style the message now. Our App.vue
file should look like this:
{{ message }}
export default { data() { return { message: 'Hello world!', }; }, }; .message { font-size: 18px; font-family: 'Roboto', sans-serif; color: blue; }
When we serve our application, we will have an input with a message of Hello World
below it. The input is bound to the message
variable, so as we type, we change the
content. Go ahead, type into the input to change the
content.
content.Now go back to your editor, and below the
tag, add the following:
Some Other Message
Save your App.vue
and watch what happens.
The h2
we just updated by typing in our input reverted back to Hello World
. This is because the browser actually refreshes, and the script tag and page are loaded again. In other words, we were not able to maintain the state of our application. This may not seem like a big deal, but as you are testing your application and adding data to it, it will be frustrating if your app “resets” every time. Fortunately, Webpack offers us a solution called Hot Module Replacement.
The hot module replacement is a plugin provided by Webpack itself. Up until this point, we have not used the Webpack object itself in our configuration file. However, we will now import Webpack so we can access the plugin.
In addition to the plugin, we will pass one additional option to Webpack, the devServer
option. In that option, we will set hot
to true
. Also, we will make an (optional) update to our build workflow: We will open the browser window automatically when we run npm run serve
. We do this by setting open
to true
which is also inside the devServer
option.
const HtmlWebpackPlugin = require('html-webpack-plugin'); const VueLoaderPlugin = require('vue-loader/lib/plugin'); const webpack = require('webpack'); module.exports = { entry: './src/main.js', module: { rules: [ { test: /\.js$/, use: 'babel-loader' }, { test: /\.vue$/, use: 'vue-loader' }, { test: /\.css$/, use: ['vue-style-loader', 'css-loader']}, ] }, devServer: { open: true, hot: true, }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html', }), new VueLoaderPlugin(), new webpack.HotModuleReplacementPlugin(), ] };
Notice that we’ve imported Webpack so we could access the hotModuleReplacementPlugin
. We’ve added that to the plugins
array, and then told Webpack to use it with hot: true
. We open the browser window automatically when we serve the application with open: true
.
Run npm run serve
:

The browser window should open, and if you open your dev tools, you should notice a slight change in the output. It now tells us hot module replacement is enabled. Let’s type in our input to change the
content. Then, change theh3
tag to read: One More Message
.
Save your file and notice what happens.
The browser doesn't refresh, but our
change is reflected! The message we typed in the input remains, but the h3
updates. This allows our application to keep it’s state while we edit it.
Step 7: Building our project
So far, we’ve served our application. But, what if we want to build our application so we can distribute it?
If you noticed, when we serve our application, no files are created. Webpack creates a version of these files that only exist in temporary memory. If we want to distribute our Hello World app to our client, we need to build the project.
This is very simple. Just like before, we will create a script in our package.json file to tell Webpack to build our project. We will use webpack
as the command instead of webpack-dev-server
. We will pass in the --mode production
flag as well.
We will also use the rimraf
package first to delete any previous builds we may have. We do this simply by rimraf dist
.
dist
is the folder Webpack will automatically create when it builds our project. “Dist” is short for distribution–i.e. we are “distributing” our applications code.
The rimraf dist
command is telling therimraf
package to delete the dist
directory. Make sure you don’t rimraf src
by accident!
Webpack also offers a plugin that will accomplish this cleaning process called clean-webpack-plugin
. I chose dist
show an alternative way.
Our package.json file should look like this:
{ "name": "hello-world", "version": "1.0.0", "description": "", "main": "main.js", "scripts": { "clean": "rimraf dist", "build": "npm run clean && webpack --mode production", "serve": "webpack-dev-server --mode development" }, "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.1.6", "@babel/preset-env": "^7.1.6", "babel-loader": "^8.0.4", "css-loader": "^1.0.1", "html-webpack-plugin": "^3.2.0", "rimraf": "^2.6.2", "vue": "^2.5.17", "vue-loader": "^15.4.2", "vue-style-loader": "^4.1.2", "vue-template-compiler": "^2.5.17", "webpack": "^4.26.0", "webpack-cli": "^3.1.2", "webpack-dev-server": "^3.1.10" }, "dependencies": {} }
There are three things to notice:
- I’ve created a separate
clean
script so we can run it independently of our build script. npm run build
will call the independentclean
script we’ve created.- I have
&&
betweennpm run clean
andwebpack
. This instruction says: “runnpm run clean
first, then runwebpack
”.
Let’s build the project.
npm run build
Webpack creates a dist
directory, and our code is inside. Since our code makes no HTTP requests, we can simply open our index.html
file in our browser and it will work as expected.
If we had code that was making HTTP requests, we would run into some cross-origin errors as we made those requests. We would need to run that project from a server for it to work.
Let’s examine the index.html
that Webpack created in the browser and the code editor.

If we open it in our editor or take a look at the source code in our dev tools you will see Webpack injected the script tag. In our editor though, you won’t see the styles because the style tag is injected dynamically at runtime with JavaScript!
Also, notice our development console information is no longer present. This is because we passed the --production
flag to Webpack.
Conclusion
Understanding the build process behind the frameworks you use will help you to better understand the framework itself. Take some time to try to build an Angular, React or another Vue Project without the use of the respective CLIs. Or, just build a basic three-file site (index.html, styles.css, and app.js), but use Webpack to serve and build a production version.
Thanks for reading!
woz