search
HomeWeb Front-endJS TutorialDetailed explanation of Vue template file packaging and configuration steps

This time I will bring you a detailed explanation of the Vue template file packaging and configuration steps. What are the precautions for Vue template file packaging and configuration? The following is a practical case, let's take a look.

1、github

Github address:

https://github.com/MengFangui/VueProjectTemplate

2. Webpack configuration

(1) Basic configuration webpack.base.config.js

const path = require('path');
//处理共用、通用的js
const webpack = require('webpack');
//css单独打包
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
 //入口文件
 entry: {
  main: './src/main',
  vendors: './src/vendors'
 },
 output: {
  path: path.join(dirname, './dist')
 },
 module: {
  rules: [
   //vue单文件处理
   {
    test: /\.vue$/,
    use: [{
     loader: 'vue-loader',
     options: {
      loaders: {
       less: ExtractTextPlugin.extract({
        //minimize 启用压缩
        use: ['css-loader?minimize', 'autoprefixer-loader', 'less-loader'],
        fallback: 'vue-style-loader'
       }),
       css: ExtractTextPlugin.extract({
        use: ['css-loader', 'autoprefixer-loader', 'less-loader'],
        fallback: 'vue-style-loader'
       })
      }
     }
    }]
   },
   //iview文件夹下的js编译处理
   {
    test: /iview\/.*?js$/,
    loader: 'babel-loader'
   },
   //js编译处理
   {
    test: /\.js$/,
    loader: 'babel-loader',
    exclude: /node_modules/
   },
   //css处理
   {
    test: /\.css$/,
    use: ExtractTextPlugin.extract({
     //minimize 启用压缩
     use: ['css-loader?minimize', 'autoprefixer-loader'],
     fallback: 'style-loader'
    })
   },
   //less处理
   {
    test: /\.less/,
    use: ExtractTextPlugin.extract({
     use: ['css-loader?minimize', 'autoprefixer-loader', 'less-loader'],
     fallback: 'style-loader'
    })
   },
   //图片处理
   {
    test: /\.(gif|jpg|png|woff|svg|eot|ttf)\??.*$/,
    loader: 'url-loader?limit=1024'
   },
   //实现资源复用
   {
    test: /\.(html|tpl)$/,
    loader: 'html-loader'
   }
  ]
 },
 resolve: {
  //自动扩展文件后缀名,意味着我们require模块可以省略不写后缀名
  extensions: ['.js', '.vue'],
  //模块别名定义,方便后续直接引用别名,无须多写长长的地址
  alias: {
   'vue': 'vue/dist/vue.esm.js'
  }
 }
};
(2) Development environment configuration webpack.dev.config.js

//处理共用、通用的js
const webpack = require('webpack');
//处理html模板
const HtmlWebpackPlugin = require('html-webpack-plugin');
//css单独打包
const ExtractTextPlugin = require('extract-text-webpack-plugin');
//合并配置
const merge = require('webpack-merge');
const webpackBaseConfig = require('./webpack.base.config.js');
//fs模块用于对系统文件及目录进行读写操作
const fs = require('fs');
//编译前用node生成一个env.js的文件,用来标明当前是开发(development)还是生产环境(production)
fs.open('./src/config/env.js', 'w', function(err, fd) {
 const buf = 'export default "development";';
 fs.write(fd, buf, 0, buf.length, 0, function(err, written, buffer) {});
});
module.exports = merge(webpackBaseConfig, {
 //打包代码的同时生成一个sourcemap文件,并在打包文件的末尾添加//# souceURL,注释会告诉JS引擎原始文件位置
 devtool: '#source-map',
 output: {
  //线上环境路径
  publicPath: '/dist/',
  filename: '[name].js',
  chunkFilename: '[name].chunk.js'
 },
 plugins: [
  //css单独打包
  new ExtractTextPlugin({
   filename: '[name].css',
   allChunks: true
  }),
  //通用模块编译
  new webpack.optimize.CommonsChunkPlugin({
   //提取的公共块的块名称(chunk)
   name: 'vendors',
   //生成的通用的文件名
   filename: 'vendors.js'
  }),
  new HtmlWebpackPlugin({
   //输出文件
   filename: '../index.html',
   //模板文件
   template: './src/template/index.ejs',
   //不插入生成的 js 文件,只是单纯的生成一个 html 文件
   inject: false
  })
 ]
});
(3) Online environment configuration webpack.prod.config.js

//处理共用、通用的js
const webpack = require('webpack');
//处理html模板
const HtmlWebpackPlugin = require('html-webpack-plugin');
//css单独打包
const ExtractTextPlugin = require('extract-text-webpack-plugin');
//合并配置
const merge = require('webpack-merge');
const webpackBaseConfig = require('./webpack.base.config.js');
//fs模块用于对系统文件及目录进行读写操作
const fs = require('fs');
//编译前用node生成一个env.js的文件,用来标明当前是开发(development)还是生产环境(production)
fs.open('./src/config/env.js', 'w', function (err, fd) {
 const buf = 'export default "production";';
 fs.write(fd, buf, 0, buf.length, 0, function (err, written, buffer){});
});
module.exports = merge(webpackBaseConfig, {
 output: {
  //线上环境路径
  publicPath: 'dist/',
  filename: '[name].[hash].js',
  chunkFilename: '[name].[hash].chunk.js'
 },
 plugins: [
  new ExtractTextPlugin({
   //css单独打包
   filename: '[name].[hash].css',
   allChunks: true
  }),
  //通用模块编译
  new webpack.optimize.CommonsChunkPlugin({
   //提取的公共块的块名称(chunk)
   name: 'vendors',
   //生成的通用的文件名
   filename: 'vendors.[hash].js'
  }),
  new webpack.DefinePlugin({
   'process.env': {
    NODE_ENV: '"production"'
   }
  }),
  //js压缩
  new webpack.optimize.UglifyJsPlugin({
   compress: {
    warnings: false
   }
  }),
  new HtmlWebpackPlugin({
   //输出文件
   filename: '../index_prod.html',
   //模板文件
   template: './src/template/index.ejs',
   //不插入生成的 js 文件,只是单纯的生成一个 html 文件
   inject: false
  })
 ]
});
(4) package.json file

{
 "name": "iview-project",
 "version": "2.1.0",
 "description": "A base project with Vue.js2、Vue-Router、webpack2 and with iView2.",
 "main": "index.js",
 "scripts": {
 "init": "webpack --progress --config webpack.dev.config.js",
 "dev": "webpack-dev-server --content-base ./ --open --inline --hot --compress --history-api-fallback --config webpack.dev.config.js",
 "build": "webpack --progress --hide-modules --config webpack.prod.config.js"
 },
 "repository": {
 "type": "git",
 "url": "git+https://github.com/iview/iview-project.git"
 },
 "author": "Aresn",
 "license": "MIT",
 "dependencies": {
 "vue": "^2.2.6",
 "vue-router": "^2.2.1",
 "iview": "^2.0.0-rc.8"
 },
 "devDependencies": {
 "autoprefixer-loader": "^2.0.0",
 "babel": "^6.23.0",
 "babel-core": "^6.23.1",
 "babel-loader": "^6.2.4",
 "babel-plugin-transform-runtime": "^6.12.0",
 "babel-preset-es2015": "^6.9.0",
 "babel-runtime": "^6.11.6",
 "css-loader": "^0.23.1",
 "extract-text-webpack-plugin": "^2.0.0",
 "file-loader": "^0.8.5",
 "html-loader": "^0.3.0",
 "html-webpack-plugin": "^2.28.0",
 "less": "^2.7.1",
 "less-loader": "^2.2.3",
 "style-loader": "^0.13.1",
 "url-loader": "^0.5.7",
 "vue-hot-reload-api": "^1.3.3",
 "vue-html-loader": "^1.2.3",
 "vue-loader": "^11.0.0",
 "vue-style-loader": "^1.0.0",
 "vue-template-compiler": "^2.2.1",
 "webpack": "^2.2.1",
 "webpack-dev-server": "^2.4.1",
 "webpack-merge": "^3.0.0"
 },
 "bugs": {
 "url": "https://github.com/iview/iview-project/issues"
 },
 "homepage": "https://www.iviewui.com"
}

ps: Let’s see how to use webpack to package vue projects?

1. Install nodejs: Using webpack for packaging requires npm, npm (node ​​package manager) is the package manager of nodejs, which is used for node plug-in management (including installation, uninstallation, dependency management, etc.), so you need to download and install nodejs first, and use npm after the installation is complete. -v Check whether the installation is complete;

2. Install cnpm (this step is not necessary): Because the npm installation plug-in is downloaded from a foreign website, abnormalities can easily occur due to network influence. cnpm is a complete npmjs.org mirror, you can use this instead of the official version (read-only). The synchronization frequency is currently every 10 minutes to ensure that it is synchronized with the official service as much as possible. Use npm install -g cnpm --registry=https://registry.npm.taobao.org installation, you can use cnpm instead of npm later;

3. Install the vue-cli scaffolding globally, npm install -g vue-cli (install to the current directory without adding -g; install to the node directory of the system with -g). After the installation is completed, use vue -V to view;

4. Create a new project based on the webpack template (download the template); use vue init webpack my-project (project folder name); then after a series of settings, a vue template will be downloaded;

5. cd my-project to enter the project folder; use the npm install command to install the dependencies in the package.json file. The relevant components will be downloaded according to the dependencies of the front-end project and stored in the node_modules folder of the project directory;

6. After installing the node_modules dependencies, use the command npm run dev

to start the project (dev is configured in the package.json file).

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the use of Vue filters

How to configure the React Native development environment with VSCode

The above is the detailed content of Detailed explanation of Vue template file packaging and configuration steps. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool