Hogyan hozzunk létre egy Vue.js alkalmazást egyfájlos összetevők használatával, a CLI nélkül.

A cikkhez hasznos lehet a Vue egyetlen fájl összetevőinek (SFC) és a Node Package Manager (NPM) megértése.

A keretrendszer parancssori felülete vagy a CLI az előnyös módszer a projekt állványozására. Ez biztosítja a fájlok, mappák és konfiguráció kiindulópontját. Ez az állvány fejlesztési és építési folyamatot is biztosít. A fejlesztési folyamat lehetővé teszi a projekt szerkesztésekor bekövetkező frissítések megtekintését. A felépítési folyamat létrehozza a termelésben felhasználandó fájlok végleges verzióját.

A Vue.js („Vue”) telepítése és futtatása parancsfájlcímkével történhet, amely a Vue tartalomszolgáltató hálózatra (CDN) mutat. Nincs szükség építési vagy fejlesztési folyamatra. De ha Vue egyfájlos összetevőket (SFC) használ, akkor ezeket a fájlokat olyanra kell konvertálnia, amelyet a böngésző megért. A fájlokat konvertálni kell Hyper-Text Markup Language (HTML), Cascading Style Sheets (CSS) és JavaScript (JS) fájlokká. Ebben az esetben fejlesztési és építési folyamatot kell használni.

Ahelyett, hogy a Vue CLI-re támaszkodnánk a projekt állványozásában és egy fejlesztési és építési folyamat biztosításában, a semmiből építünk egy projektet. A Webpack segítségével elkészítjük saját fejlesztési és építési folyamatunkat.

Mi a Webpack?

A Webpack egy modulcsomagoló. Egyesíti a több fájlból származó kódot egybe. A Webpack előtt a felhasználó minden JavaScript fájlhoz szkript címkét adott. Bár a böngészők lassan támogatják az ES6 modulokat, továbbra is a Webpack az elsődleges módja a moduláris kód létrehozásának.

Amellett, hogy modulcsomagoló, a Webpack képes átalakítani a kódot is. Például Webpack vehet modern JavaScript (ECMAScript 6+), és alakítani ECMAScript 5. Míg Webpack kötegek maga a kód, mert átalakítja a kódot rakodók és beépülő modulok. Gondoljon a betöltőkre és a beépülő modulokra, mint a Webpack kiegészítőire.

Webpack és Vue

Az egyfájlú összetevők lehetővé teszik számunkra, hogy egy teljes összetevőt (struktúrát, stílust és funkciót) egy fájlba építsünk. És a legtöbb kódszerkesztő szintaxis kiemeléssel és átmetszéssel látja el ezeket az SFC-ket.

Figyelje meg, hogy a fájl vége .vue. A böngésző nem tudja, mit kezdjen ezzel a kiterjesztéssel. A Webpack a betöltők és a beépülő modulok segítségével átalakítja ezt a fájlt a böngésző által használt HTML, CSS és JS fájlokká.

A projekt: Hozzon létre egy Hello World Vue alkalmazást egyetlen fájl összetevőinek felhasználásával.

1. lépés: Készítse el a projekt szerkezetét

A legalapvetőbb Vue projekt tartalmazni fog egy HTML-t, JavaScript-et és egy Vue-fájlt (a .vue végződésű fájl ). Ezeket a fájlokat egy nevű mappába helyezzük src. A forrás mappa segít elválasztani az általunk írt kódot a Webpack által végül összeállított kódtól.

Mivel a Webpack alkalmazást fogjuk használni, szükségünk van egy Webpack konfigurációs fájlra.

Ezenkívül a Bábel nevű fordítót fogjuk használni. A Bábel lehetővé teszi számunkra, hogy ES6 kódot írjunk, amelyet aztán fordít az ES5-be. A Babel egyike azoknak a kiegészítő funkcióknak a Webpack számára. Babelnek szüksége van egy konfigurációs fájlra is.

Végül, mivel NPM-et használunk, lesz egy node_modules mappánk és egy package.json fájlunk is. Ezek automatikusan létrejönnek, amikor inicializáljuk projektünket NPM projektként, és elkezdjük telepíteni a függőségeinket.

A kezdéshez hozzon létre egy nevű mappát hello-world. A parancssorból váltson át arra a könyvtárra, és futtassa npm init. Kövesse a képernyőn megjelenő utasításokat a projekt létrehozásához. Ezután hozza létre a többi mappát (kivéve node_modules) a fent leírtak szerint. A projekt felépítésének így kell kinéznie:

2. lépés: Telepítse a függőségeket

Itt van egy gyors áttekintés az általunk használt függőségekről:

vue : A JavaScript keretrendszer

vue-loader és vue-template-compiler : Vue fájljaink JavaScript-fé konvertálására szolgál.

webpack : Az az eszköz, amely lehetővé teszi számunkra, hogy átadjuk kódunkat néhány átalakításon keresztül, és egy fájlba csomagoljuk.

webpack-cli: A Webpack parancsok futtatásához szükséges.

webpack-dev-server : Bár nem szükséges a kis projektünkhöz (mivel nem fogunk HTTP-kéréseket küldeni), a projektünket továbbra is egy fejlesztői kiszolgálóról fogjuk "kiszolgálni".

babel-loader : Alakítsa át az ES6 kódunkat ES5-be. (Segítségre van szüksége a következő két függőségtől.)

@ babel / core és @ babel / preset-env : A Babel önmagában nem tesz semmit a kódoddal. Ez a két „kiegészítő” lehetővé teszi számunkra, hogy az ES6 kódunkat ES5 kódokká alakítsuk át.

css-loader: Felveszi a CSS-t, amelyet a sajátunkba írunk.vuefájlokat vagy bármilyen CSS-t, amelyeket importálhatunk bármelyik JavaScript-fájlunkba, és megoldhatjuk a fájlok elérési útját. Más szavakkal, derítse ki, hol van a CSS. Ez egy másik rakodógép, amely önmagában nem sokat fog tenni. Szükségünk van a következő betöltőre, hogy valóban tegyen valamit a CSS-sel.

vue-style-loader : Vegyük a tőlünk kapott CSS-t, és adjuk css-loaderbe a HTML fájlunkba. Ez létrehoz egy stíluscímkét és befecskendezi azt a HTML dokumentumunk fejébe.

html-webpack-plugin : Fogja az index.html fájlt, és fecskendezze be a mellékelt JavaScript fájlunkat a fejébe. Ezután másolja ezt a fájlt adistmappába.

rimraf : Lehetővé teszi számunkra a parancssorból a fájlok törlését. Ez jól jön, ha többször elkészítjük a projektünket. Ezt felhasználjuk a régi buildek törléséhez.

Telepítsük most ezeket a függőségeket. A parancssorból futtassa:

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

Megjegyzés: A végén található „-D” minden függőséget fejlesztési függőségként jelöl meg a csomagunkban.json. Az összes függőséget egy fájlba csomagoljuk, így kis projektünknél nincsenek termelési függőségek.

3. lépés: Hozza létre a fájlokat (a Webpack konfigurációs fájlunk kivételével).

 {{ 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'], }

Eddig a pontig semmi sem tűnhet túl idegennek. Minden fájlt nagyon alaposan megtartottam. Csak minimális CSS-t és JS-t adtam hozzá, hogy működés közben lássam a munkafolyamatunkat.

4. lépés: A Webpack utasításainak megadása

A Webpack minden konfigurációjához hozzáférésre van szükség. Két utolsó dolgot kell tennünk: Mondja meg a Webpacknak, hogy mit kell tennie, és futtassa a Webpack-ot.

Az alábbiakban a Webpack konfigurációs fájl ( webpack.config.js) található. Hozza létre ezt a fájlt a projektek gyökérkönyvtárában. Soronként megbeszéljük, mi történik.

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(), ] };

1. és 2. sor: Az alábbiakban használt két beépülő modult importáljuk. Vegye figyelembe, hogy a rakodógépeinket általában nem kell importálni, csak a bővítményeinket. Esetünkben pedig avue-loader (amelyet a 9. sorban használunk) működéséhez pluginra is szükség van (azonban például Bábel nem).

4. sor: A konfigurációnkat objektumként exportáljuk. Ez hozzáférést biztosít számunkra, amikor a Webpack parancsokat futtatjuk.

5. sor: Ez a belépési modulunk. A Webpack-nak szüksége van egy helyre, ahol elindulhat. A fájlunkba néz, main.jsmajd ettől a ponttól kezdi átfésülni a kódunkat.

6. és 7. sor: Ez a modul objektum. Itt elsősorban egy sor szabályt adunk át. Minden szabály megmondja a Webpacknak, hogyan kell kezelni bizonyos fájlokat. Tehát, míg a Webpack a belépési pontot használja a main.jskód fésülésének megkezdéséhez, a szabályokat használja a kód átalakításához.

8. sor (szabály): Ez a szabály arra utasítja a Webpack-et, hogy a babel-loadervégződő fájlokra használja a .js. Ne feledje, hogy Babel átalakítja az ES6 + -t ES5-re.

9. sor (szabály): Ez a szabály utasítja a Webpack használatátvue-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.vuefile 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.

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:

  1. I’ve created a separate clean script so we can run it independently of our build script.
  2. npm run build will call the independent clean script we’ve created.
  3. I have && between npm run clean and webpack. This instruction says: “run npm run clean first, then run webpack”.

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