首先建立项目文件夹 vueTest,执行:css
cd vueTest && npm init
安装webpack和vuehtml
npm i -D webpack
npm i -D webpack-cli
npm i -S vue
建立下面的项目目录:vue
App.vue :node
<template> <h1>Hello {{ msg }}</h1> </template> <script> export default { data(){ return { msg: 'Vue.js' } } } </script> <style scoped> h1{ font-family: 'Courier New'; color: red; } </style>
main.js :webpack
import Vue from 'vue'; import App from './App.vue'; new Vue({ el: '#app', render: h => h(App) });
而后开始写webpack配置文件,写以前先安装各类loaderweb
npm i -D vue-loader css-loader vue-template-compiler
还须要用extract-text-webpack-plugin插件将vue文件中的样式提取出来npm
npm i -D extract-text-webpack-plugin
若是webpack版本是4.0及以上请执行下面的命令:json
npm i -D extract-text-webpack-plugin@next
webpack.config.js :浏览器
const path = require('path'); const VueLoaderPlugin = require('vue-loader/lib/plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { entry: './main.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, './dist'), }, resolve: { extensions: ['.js', '.vue', '.json'], }, module: { rules: [ { test: /\.vue$/, use: ['vue-loader'], exclude: /node_modules/ }, { test: /\.css$/, use: ExtractTextPlugin.extract({ use: ['css-loader'] }), exclude: /node_modules/ } ] }, plugin: [ new VueLoaderPlugin(), new ExtractTextPlugin('style.css') ] }
而后在package.json里写一个启动脚本app
{ "name": "vuetest", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack --config webpack.config.js" }, "author": "", "license": "ISC", "devDependencies": { "css-loader": "^1.0.0", "extract-text-webpack-plugin": "^4.0.0-beta.0", "vue-loader": "^15.2.6", "vue-template-compiler": "^2.5.17", "webpack": "^4.16.4", "webpack-cli": "^3.1.0" }, "dependencies": { "vue": "^2.5.17" } }
执行 npm run build 便可成功编译:
编译后的项目结构:
在index.html中写入:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" href="./dist/style.css"> </head> <body> <div id="app"></div> <script src="./dist/bundle.js"></script> </body> </html>
打开浏览器就看看到效果了: