vue-cli是怎么通过webpack把js文件引入index.html的过程呢?
vue新手在用vue-cli写项目时候会发现,项目目录下index.html并没有通过标签引入任何js。index.html如下:

<!DOCTYPE html>
<head>
</meta charsets="utf-8">
</meta name='viewport' content='width=device-width,user-scalable=no,scalable=1.0'>
<head>
<body>
  <div id="app"></div>
<body>
</html>

那到底是怎么引入js的呢?首先打开package.json,找到script

"scripts": {
  "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
  "start": "npm run dev",
  "build": "node build/build.js"
},

执行命令npm run dev ,这时你会看到你创建的vue项目启动起来,所以我们一步步看,执行这个命令,需要找到webpack.dev.conf.js”这个文件,打开它
我们看到

'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')

它引入了很多插件,这里我们不管其他的,只看两个,webpack.base.conf ;html-webpack-plugin
打开webpack.base.conf.js,我们看到

'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}

module.exports = {
  context: path.resolve(__dirname, '../'),
  entry: {
    app: './src/main.js'
  },

入口文件指向main.js,打开main.js,如下

import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import store from "./store"
import echarts from 'echarts'

Vue.config.productionTip = false
Vue.prototype.$echarts = echarts 
Vue.use(ElementUI)


/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App }
})

这里绑定了id为app的元素,然后我们打开第二个文件html-webpack-plugin,这个plugin是帮做我们配置html文件中js文件的引入的,有了这个plugin我们就不用再用在html中加入标签这么傻的方式引入js文件了在node-modules中,打开index.js

function HtmlWebpackPlugin (options) {
  // Default options
  this.options = _.extend({
    template: path.join(__dirname, 'default_index.ejs'),
    filename: 'index.html',
    hash: false,

我们发现这不是有index.html吗,所以通过一系列复杂的关系我们得出:启动命令后,通过webpack的文件决定main.js作为app的入口,将main.js通过id绑定在index.html上

Logo

前往低代码交流专区

更多推荐