最近在学习用vue-cli创建项目, 对入口文件main.js如何挂载到#app产生了兴趣.
public目录下有个index.html文件
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>
<%= htmlWebpackPlugin.options.title %>
</title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
最开始以为main.js将根组件App挂载到这里, 后来将index.html彻底删除, 项目能正常运行, 检查浏览器源代码如下:
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Vue App</title>
<link href="/js/app.js" rel="preload" as="script"><link href="/js/chunk-vendors.js" rel="preload" as="script"></head>
<body>
<div id="app"></div>
<script type="text/javascript" src="/js/chunk-vendors.js"></script><script type="text/javascript" src="/js/app.js"></script></body>
</html>
这个代码应该是后生成的, 跟原来的index.html相比增加了script标签, 经过搜索发现应该是HTML Webpack Plugin插件起作用了. 查询html-webpack-plugin文档html-webpack-plugin - npm
发现它有很多配置项, 跟此有关的配置项如下:
filename属性,可以用于配置生成的HTML文件的文件名,默认为:index.html;
template属性, 指定一个路径比如: template: './src/public/index.html', 基于这个路径下的html文件生成打包输出的新html文件
templateContent, 指定模板内容, 用于替换template属性,
目前来看, vue-cli构建的项目使用了templateContent属性, 并且指定的模板中有id="app"这样的代码.
为了验证用webpack构建了一个简单项目.
将原先public目录下的index.html删除
再修改webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
const htmlPlugin = new HtmlWebpackPlugin({
// template: './src/public/index.html',
filename: 'index.html',
templateContent: `
<html>
<body>
<div id="app"></div>
</body>
</html>
`
})
取消基于./src/public/index.html生成打包的html文件, 而是通过templateContent指定模板并将由Vue管理的#app也写在这里.
index.js
import $ from 'jquery';
import './css/1.css';
import App from './components/App.vue';
import Vue from 'vue';
$(function() {
$('li:odd').css('backgroundColor', 'orange');
$('li:even').css('backgroundColor', 'darkblue');
});
class Person {
static info = 'aaa';
}
const vm = new Vue({
// el: '#app',
render: h => h(App)
}).$mount('#app');
console.log(Person.info);
console.log(App);
App.vue
<template>
<div>
<h1>这是 APP 根组件</h1>
</div>
</template>
<script>
export default {
data(){
return {};
}
}
</script>
<style scoped>
h1 {
color: red;
}
</style>
通过浏览器查询源码
<html>
<body>
<div id="app"></div>
<script type="text/javascript" src="./bundle.js"></script></body>
</html>
由此可以得出结论:
由Vue-cli构建的项目不需要index.html文件, 可以通过webpack的插件html-webpack-plugin通过配置属性而打包生成.