webpack打包vue项目,vue的template内容未显示的问题解决方案

直接上代码

根据webpack官网教程安装了相关的组件

npm install -D babel-loader @babel/core @babel/preset-env webpack

执行完成后,以下黄色标注代码被安装完成

package.json

{
  "name": "meetwebpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.12.10",
   "@babel/plugin-transform-runtime": "^7.12.10",
    "@babel/preset-env": "^7.12.11",
  "babel-loader": "^7.1.5",
  "babel-preset-es2015": "^6.24.1",
    "css-loader": "^5.0.1",
    "file-loader": "^6.2.0",
    "less": "^4.0.0",
    "less-loader": "^7.2.0",
    "style-loader": "^2.0.0",
    "url-loader": "^4.1.1",
    "webpack": "^5.11.0",
  "webpack-cli": "^4.2.0"
  },
  "dependencies": {
    "babel-core": "^7.0.0-bridge.0",
  "regenerator-runtime": "^0.13.7",
  "vue": "^2.6.12"
  }
}

如果你这里之前使用的是babel-core 6.x突然升级版本到@babel/core 7.x可能会由于依旧使用低版本报错,例如我遇到的报错代码为:Requires Babel “^7.0.0-0”, but was loaded with “6.26.3”,你可能会用到以下代码:

npm i babel-core@^7.0.0-bridge.0 @babel/core regenerator-runtime

运行之后会出现上图标绿的代码。

 

然后根据官网文档在配置文件中进行了如下配置

webpack.config.js

rules: [
  // the 'transform-runtime' plugin tells Babel to
  // require the runtime instead of inlining it.
  {
    test: /\.m?js$/,
    exclude: /(node_modules|bower_components)/,
    use: {
      loader: 'babel-loader',
      options: {
        presets: ['@babel/preset-env'],
        plugins: ['@babel/plugin-transform-runtime']
      }
    }
  }
]

main.js

//使用vue开发
import Vue from 'vue'

const app = new Vue({
  el:'#app',
  data:{
    message:'你好'
  }
})

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <div id="app">
    <h2>{{message}}</h2>
  </div>

</body>
<script src="../webpack配置vue/dist/main.js"></script>
</html>

此时我打包运行页面之后发现页面为空白,并且控制台未报错,之前设置的其他内容依旧可以输出,但是vue模板内的内容未输出到页面,并且在控制台没有看到此div的结构。

搜索了一些解决方案后我发现可能是runtime-only无法编译模板,这里我们需要使用runtime-compiler,使用runtime-only使用的是vue.runtime.js文件,无法编译模板,所以需要修改成使用runtime-compiler

随即我尝试了以下方法

方法1:

在webpack中添加别名配置,从而让它运行指定的文件

resolve:{
    //alias:别名
    alias:{
      'vue$':'vue/dist/vue.esm.js'
    }
  }

这里要注意一下‘Vue$’不是随便写的,它是指你自定义的Vue名字,也就是导入时用的名字,因为Vue导出使用export default所以这里可以自定义名字。‘自定义名字$’是这个意思。特别注意:$是在后面的,我之前跟着一些教程写在了前面结果不报错也不显示

方法2:

直接修改main.js内的引入

import Vue from 'vue/dist/vue.esm.js'

修改之后成功显示模板内的内容

posted @ 2020-12-25 01:01  又拿代码换酒钱  阅读(1857)  评论(0编辑  收藏  举报