javascript 文件在 vue cli html 模板中不工作

javascript file is not working in vue cli html template

我正在使用 vue cli 创建一个多页面网络应用程序。 文件结构如下:

- public
   - index.html
   - tables.html
   - us.html
   - guide.html
- src
   - main.js

而 main.js 是:

import Vue from 'vue'
import router from './router'

Vue.config.productionTip = false

console.log('hello world!');

let appExists = document.querySelector('#app') != undefined;
if(appExists){
  new Vue({
    router,
    render: h => h(App),
    mounted(){
      console.log('hi!');
    }
  }).$mount('#app')
}

我在找什么:

我想将 main.js 文件加载到 tables.html 文件中。

发生了什么:

main.js 在除 index.html.

之外的任何文件中均无效

我做了什么:

当我搜索时,我意识到 vue cli 仅在 index.html 中加载 main.js 而不是在任何其他文件中。当我尝试在 tables.html 中使用 <script src="/src/main.js"></script> 加载 main.js 时,我总是收到错误 Uncaught SyntaxError: expected expression, got '<'。我尝试了一些解决方案,例如 https://cli.vuejs.org/config/#pages,但它根本没有改变任何东西。

问题是:

如何在其他文件中使用 main.js?

我明白了。 vue cli 中的一切都与 webpack 插件的组合一起工作。

将文件连接在一起的插件称为“HtmlWebpackPlugin”。

首先,使用以下方式安装插件:

npm i html-webpack-plugin

然后你可以告诉这个插件:“嘿,我的项目中有另一个页面!请连接 main.js 到它”通过在 vue.config.js:

中编写下面的代码
const HtmlWebpackPlugin = require('html-webpack-plugin');


    module.exports = {
      configureWebpack: {
          plugins: [
            new HtmlWebpackPlugin({
              filename: 'tables.html',
              template: './public/tables.html',
            }),
            new HtmlWebpackPlugin({
              filename:'index.html',
              template: './public/index.html',
            }),
          ]
      }
    }

希望对遇到同样问题的其他人有所帮助!