本文将介绍如何用webpack4搭建一个vue的项目,webpack基本语法这里不作介绍,有问题能够参考webpack中文文档css
1.建立一个文件夹,咱们暂且称为webpackTest,打开终端,并进入到改文件目录下,初始化npm 项目, 这一步执行完会出现一个package.json的文件html
npm init
2.安装所须要的依赖:webpack vue vue-loader css-loader vue-template-compilervue
npm install webpack vue vue-loader css-loader vue-template-compiler
3.建立文件夹src,并在里面建立两个文件App.vue和index.js
3.1 src/App.vue下的代码为webpack
<template> <div id="app">{{text}}</div> </template> <script> export default { data () { return { text: "hello word" } } } </script>
3.2 src/index.js下的代码为git
import Vue from 'vue'; import App from './App.vue'; const root = document.createElement('div'); document.body.appendChild(root); new Vue({ render : (h) => h(App) }).$mount(root)
4.安装HtmlWebpackPlugin,该插件可自定生成index.html,也能够自定义html模板,想了解更多查看HtmlWebpackPlugingithub
npm install --save-dev html-webpack-plugin
5.新建webpack.config.js,代码以下web
const path = require('path') // 新加入 VueLoaderPlugin const VueLoaderPlugin = require('vue-loader/lib/plugin') var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: path.join(__dirname, 'src/index.js'), output: { filename: 'bundle.js', path: path.join(__dirname, 'dist') }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader' },{ test: /\.css$/, loader: 'css-loader' } ] }, plugins: [ new VueLoaderPlugin(), new HtmlWebpackPlugin() ] }
6.在package.js > script下添加代码以下:npm
"build": "webpack --config webpack.config.js"
执行npm run build,提示安装webpack-cli,输入yes,打包成功后,在dist下生成了bundle.js和index.html,用浏览器打开index.html,浏览器输出hello word
7.使用webpack-dev-server 搭建一个简单的 web 服务器,可以实时从新加载(live reloading)。让咱们设置如下:json
npm install --save-dev webpack-dev-server
7.1修改配置文件webpack.config.js,告诉开发服务器(dev server),在哪里查找文件,修改后的代码以下:浏览器
const path = require('path') // 加入 VueLoaderPlugin const VueLoaderPlugin = require('vue-loader/lib/plugin') var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: path.join(__dirname, 'src/index.js'), output: { filename: 'bundle.js', path: path.join(__dirname, 'dist') }, //新添加代码 devServer: { contentBase: './dist' }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader' },{ test: /\.css$/, loader: 'css-loader' } ] }, plugins: [ new VueLoaderPlugin(), new HtmlWebpackPlugin() ] }
7.2在package.json,添加"start": "webpack-dev-server --open",以下
咱们能够在命令行中运行 npm start,就会看到浏览器自动加载页面,并输出hello word,修改App.vue的text的变量为“hello word123”,保存更改,可见浏览器页面立刻更新为hello word123