单文件开发
.vue单文件开发依赖webpack的模块机制,将template、script、style封装在单文件中,代码的组织性和可复用性得到增强。
这个模块叫做"vue-loader",官方文档
手动配置webpack
- 安装依赖
npm i -D webpack webpack-cli webpack-dev-server
touch webpack.config.js
npm i -D css-loader
npm i -D vue vue-loader vue-template-compiler
一次性下载:
npm i -D webpack webpack-cli webpack-dev-server css-loader vue vue-loader vue-template-compiler
touch webpack.config.js
- 编辑node项目配置文件package.json
{
"name": "my-app",
"version": "1.0.0",
"description": "My first singe page web app...",
"private": true, // 防止意外发布
"scripts": {
"dev": "webpack-dev-server --host 0.0.0.0 --port 8080 --open" // 开发服务器脚本
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"vue": "^2.6.11",
"vue-loader": "^15.8.3",
"vue-template-compiler": "^2.6.11",
"css-loader": "^3.4.2",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.3"
}
}
- 编辑配置文件./webpack.config.js
const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
module.exports = {
mode: 'development',
devServer: {
contentBase: `${ __dirname }/dist`,
},
entry: {
index: `${__dirname}/src/js/index.js`,
},
output: {
filename: 'js/[name]/bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{ test: /.vue$/, loader: 'vue-loader', },
{ test: /.css$/, use: ['vue-style-loader', 'css-loader'], },
],
},
plugins: [ new VueLoaderPlugin(), ],
};
VueLoaderPlugin:这个插件是必须的! 它的职责是将你定义过的其它规则复制并应用到 .vue 文件里相应语言的块。例如,如果你有一条匹配 /.js$/
的规则,那么它会应用到 .vue 文件里的 <script>
块。
开始编码
src/js/index.js
import Vue from 'vue';
import Index from '../vue/index.vue';
new Vue({
el: '#app',
render: h => h(Index),
});
src/vue/index.vue
<template>
<div>
<h1>{{msg}}</h1>
</div>
</template>
<script>
export default {
data() {
return {
msg: 'Hello, Vue.js',
};
},
};
</script>
<style scoped>
* {
color: pink;
}
</style>
dist/index.html
<!DOCTYPE HTML>
<html>
<div id='app'></div>
<script src='./js/index/bundle.js'></script>
</html>
渲染结果:
模块化开发
借助url-loader模块,我们实现一张“忍者”卡片模块:
<template>
<div id='all'>
<img :src=ninja />
<div id='title'>{{ title }}</div>
</div>
</template>
<script>
import ninja from 'url-loader!./ninja.png';
export default {
data() {
return {
title: '忍者',
ninja,
};
},
};
</script>
<style scoped>
div#all {
fit-content;
border: 1px solid red;
}
div#title {
text-align: center;
}
</style>