As a beginner of the front of the small white, also want to write some high content things like other gods. But their own technology is less than home, so it can only record their own climb pit road, bit by bit to record their growth.

This is my first article, without further ado, let’s begin.


Preparations:

Before we start, let’s build our project structure. Create a new folder for web-Demo. See the following figure for the file structure



Write a little something in the file first, so that we can judge whether it is successful when debugging

//style.css * { padding: 0; margin: 0; box-sizing: border-box; } h2 { font-size: 28px; color: royalblue; }Copy the code

//index.html
<html lang="zh-CN"><head>    <meta charset="UTF-8">    <meta name="viewport" content="Width = device - width, initial - scale = 1.0 maximum - scale = 1, minimum - scale = 1, the user - scalable = no">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>Document</title></head><body>    <article id="app">        <h2>            hello word        </h2>    </article></body></html>
Copy the code

After everything is ready, the official work begins


First, build the front-end development environment based on WebPack

1. Initialize the project

Open the command line tool in the root directory (gitbash is recommended) and execute NPM init

npm initCopy the code

After that, there is some basic configuration work, such as package name, description, version number, and so on, which defaults to Enter

A package.json file is then generated in the root directory

{  
  "name": "web-demo", / / package name"version": "1.0.0"// Version number"description": ""// Project description"main": "index.js"."scripts": {
       "test": "echo \"Error: no test specified\" && exit 1"
    },
  "author": ""."license": "ISC"
}Copy the code


2. Install webpack

After WebPack 4.0, webPack-CLI must be installed separately

npm install webpack -webpack-cli -DCopy the code

After successful installation, create a new webpack.config.js file in the root directory. This is the webPack configuration file, and basically all of our configuration work will be done in this file.

General WebPack configuration items include the following

module.exports = {
    entry: ' '// Module: {}, // module: {}, // module: {}, //'development'// Environment mode configuration}Copy the code


Let’s start with the import and export files:

const path = require('path')
module.exports = {    entry: ['./app/js/main.js'], output: {//[name] means that the file name is the same as the entry file //[hash] to add ahashString filename:'[name].[hash:4].js'Path: path.resolve(__dirname,'dist')}}Copy the code

After that we open the package.json file and modify the script

"scripts": {
    "build": "webpack"To perform the packaging operation"test": "echo \"Error: no test specified\" && exit 1"
},Copy the code

We are now ready to perform the following packaging operations

npm run build Copy the code

After we run it, we should see a dist folder and a.js file generated in the project root directory




3. Parse the packaged HTML template file:

This time we need to install a plug-in, htML-webpack-plugin

npm install html-webpack-plugin -DCopy the code

After the installation is complete, configure the reference in config.js

const path = require('path'// const HtmlwebpackPlugin=require('html-webpack-plugin')
module.exports = {    entry: ['./app/js/main.js'], output: {//[name] means that the file name is the same as the entry file //[hash] to add ahashString filename:'[name].[hash:4].js'Path: path.resolve(__dirname,'dist'HtmlwebpackPlugin({template:});}, plugins:[// New HtmlwebpackPlugin({template:});'./app/views/index.html', // Template file location})]}Copy the code

Now I’m going to wrap it up again, and you should have.html.



We can run the index.html in a browser at this point



You can see that this is exactly what we wrote earlier, and the JS file is also introduced in the page.

However, it is also found that there are many. Js files in the directory because the hash is different each time. At this point we need to install a plug-in to help us solve the problem.

Install the clean-webpack-plugin, which empties the dist directory every time you pack

start

npm install clean-webpack-plugin -DCopy the code

We also need to introduce and new a class in config.js

const path = require('path'// const HtmlwebpackPlugin=require('html-webpack-plugin')const CleanWebpackPlugin=require('clean-webpack-plugin')
module.exports = {    entry: ['./app/js/main.js'], output: {//[name] means that the file name is the same as the entry file //[hash] to add ahashString filename:'[name].[hash:4].js'Path: path.resolve(__dirname,'dist'HtmlwebpackPlugin({template:});}, plugins:[// New HtmlwebpackPlugin({template:});'./app/views/index.html', // Template file location}), new CleanWebpackPlugin('dist'),// Specify the folder to empty]}Copy the code

There won’t be multiple useless.js files when you do the packaging again


4. How can you do front-end CSS less

To parse CSS files we need to install some loaders. Style – loader and CSS – loader

npm install style-loader css-loader -DCopy the code

The use of loader is somewhat different from that of plug-ins, see the code for details

const path = require('path'// const HtmlwebpackPlugin = require('html-webpack-plugin')const CleanWebpackPlugin = require('clean-webpack-plugin')
module.exports = {    entry: ['./app/js/main.js'], output: {//[name] means that the file name is the same as the entry file //[hash] to add ahashString filename:'[name].[hash:4].js'Path: path.resolve(__dirname,'dist')    },    module: {        rules: [            {                test: /\.css$/,                use: ['style-loader'.'css-loader'HtmlwebpackPlugin({template:});}}, plugins: [// new HtmlwebpackPlugin({template:});'./app/views/index.html', // Template file location}), new CleanWebpackPlugin('dist'),// Specify the folder to empty]}Copy the code

After the configuration, import the style.css file in main.js

import '.. /css/style.css'Copy the code

The packaging is done again, but we find that no CSS files are generated. Run it in your browser



As you can see, the CSS style is embedded in the style tag, we need to introduce the link.

Ask a plugin again to help us extract the CSS.

npm install mini-css-extract-plugin -DCopy the code

After installation, continue to configure config.js

const path = require('path'// const HtmlwebpackPlugin = require('html-webpack-plugin'Const CleanWebpackPlugin = require()'clean-webpack-plugin'// separate cssconst MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {    entry: ['./app/js/main.js'], output: {//[name] means that the file name is the same as the entry file //[hash] to add ahashString filename:'[name].[hash:4].js'Path: path.resolve(__dirname,'dist')    },    module: {        rules: [            {                test: / \. CSS $/, / / separation using plug-ins, do not need to style - loader use: [MiniCssExtractPlugin loader,'css-loader'}]}, plugins: [// new HtmlwebpackPlugin({// template file location:'./app/views/index.html'}), // Specify the folder to be emptied new CleanWebpackPlugin('dist'), new MiniCssExtractPlugin({// Split CSS filename filename:'style.css',}})]Copy the code

Do the packaging again



As you can see, the CSS file has been detached.



And it was introduced in link’s way.


5. Pictures are also indispensable

There are three scenarios for introducing images in real development: background images, img tags, and image fonts.

At this time, we need to use three Loaders to help us complete the above functions

npm install url-loader html-withimg-loader file-loader -DCopy the code

Configure config.js(I won’t post the full code here)

rules:[
{    test: /\.(jpe? g|png|gif)$/, use: [ { loader:'url-loader',                options: {                    limit: 8192, // Images smaller than 8K are automatically converted to base64 outputPath:'images/'}}]}, {test: /\.(htm|html)$/,        use: 'html-withimg-loader' }, {    test: /\.(eot|ttf|woff|svg)$/,        use: 'file-loader'}]Copy the code

We can modify the template file to add an IMG tag

<body>    <article id="app"<img SRC = "img SRC ="".. /img/bg.jpg" style="width:500px;" alt=cyberpunk>    </article></body>Copy the code

Do the packaging again, then run



Perfect!


6. The important — static server

You need to install a Webpack-dev-server

npm install webpack-dev-server -DCopy the code

After the installation is complete, configure config.js.

devServer: {   contentBase: './dist',   host: 'localhost'// Default localhost port: 3000, // port number open:true, // Automatically open browser}Copy the code

Also add an execution code to package.json

"scripts": {    "build": "webpack"."dev": "webpack-dev-server"."test": "echo \"Error: no test specified\" && exit 1"  },Copy the code

run

npm run devCopy the code

At this point, the application will automatically open the browser and display a page we are developing.


At this point, a simple WebPack-based front-end development environment is configured. So here we go

2. Use VUE in your project

1. Prepare, revise the documents in the project,

Add app. vue, /router/index.js, home/index.vue



2. Install the components we need

Vue, VUe-router, VUe-loader, vue-template-compiler

npm install vue vue-router vue-loader vue-template-compiler -DCopy the code

Also after installation, you need to configure it in config.js

const path = require('path'// VUE file const VueLoader = require('vue-loader/lib/plugin')
module.exports = {    entry: ['./app/js/main.js'], output: {//[name] means that the file name is the same as the entry file //[hash] to add ahashString filename:'[name].[hash:4].js'Path: path.resolve(__dirname,'dist')    },    module: {        rules: [            {                test: /\.vue$/,                loader: 'vue-loader'            }        ]    },    plugins: [        new VueLoader()    ]}Copy the code

After that, modify the entry file and the three files we created

First is the main. Js

import Vue from "vue"//vue module import App from"./App.vue"//vue import router from"./router"// Routing file for page management import'.. /css/style.css'// Style file vue.config.productionTip =false// Create a vue object new vue ({el:"#app",    router,    components: { App },    template: "<App/>",})Copy the code

App.vue

<template>    <div id="app">        <router-view/>    </div></template>
<script>export default {  name: "App"}; </script>Copy the code

index.js

import Vue from 'vue'import Router from 'vue-router'// Import the routing module import Index from'.. /home/index.vue'Use (Router) // Create a routeexport default new Router({    routes: [        {            path: "/",            name: "Index",            component: Index        }    ]})Copy the code

Index.vue — This is our home page

<template>    <div>        <h2>            helloword        </h2>    </div></template><script>exportdefault {}; </script>Copy the code

Run the server when you’re done

npm run devCopy the code

Well, it’s a blank. Take a look at the browser Console



The default vue is the Runtime version, and the full version is required to parse the vue template.

So, modify config.js. Add a Resolve so that we can load the full vue version when importing

. devServer: { contentBase:'./dist',        host: 'localhost'// Default localhost port: 3000, // port number open:true}, resolve: {alias: {            'vue': 'vue/dist/vue.js'}},...Copy the code

Ok runs again. So now we have a red Hello Word


At this point, we are ready to develop a simple VUE project


And three,

There is still some work to be done in the actual development

1. For example, using SCSS preprocessor

npm install sass-loader node-sass -DCopy the code

Configure config. Js

{
    test: /\.scss$/,
    loader: 'style-loader! css-loader! sass-loader'
}Copy the code

Change our style.css file name to style.scss

Then import ‘.. in main.js / CSS /style.css’, ‘import ‘.. /css/style.scss’

Run NPM run dev again


We also see helloWord in red in the browser

But how do you tell when the pre-SCSS is in effect? We can modify the style to use sass syntax

$red:#d31919; // define a variable h2 {font-size: 30px; color: $red; Reference this variable}Copy the code


Run NPM run dev again

This time we can see that the color of Hello Word has changed. We can review the elements



As you can see, the color value is the value of the variable we defined.


Using CSS preprocessors allows you to modularize CSS, reuse code, fast rasterization, and more. I’ll list some common SASS syntax in my next article.

Ok the end of the first article!