为什么要求不起作用,但导入起作用

问题描述 投票:0回答:1

我正在使用webpack来构建一个简单的项目,如果我使用import导入app.js,则在main.js中,效果很好。但是,如果我使用require导入文件,则vue模板将不会显示在页面上。为什么会出现此错误?babel编译导入不要求吗?如果是这样,为什么要求不起作用

使用require的结果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>  
</head>
<body>
    <!--function(e,n,r,o){return Fe(t,e,n,r,o,!0)}-->
    <h1>123</h1>
</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>  
</head>
<body>
    <div id="app"></div>
    <h1>123</h1>
</body>
</html>

main.js

const Vue = require("vue");
const router = require('vue-router')
// const app = require('./app.vue')
import app from './app.vue'


new Vue({
el: "#app",
data: {},
render: el => el(app),
// router
})

webpack.config.js

const htmlPlugin = require('html-webpack-plugin')


module.exports = {
  entry: path.join(__dirname, "./src/main.js"),

  output: {
    path: path.join(__dirname, "./dist"),
    filename: "bundle.js"
  },

  module: {
    rules: [
      { test: /\.js$/, use: "babel-loader", exclude: /node_modules/ },
      { test: /\.vue$/, use: "vue-loader" }
    ]
  },
  plugins: [
    new htmlPlugin({
      minify: {
        removeAttributeQuotes: true
      },
      hash: true,
      template: "./src/index.html"
    })
  ],
  resolve: {
    // extensions: [ '.vue'],
    alias: {
      'vue$': 'vue/dist/vue.common.js'
    }
  },
};

app.js

<template>
<div class="app-contianer">
    <h1>test</h1>
</div>
</template>
<script>
export default {
  data () {
    return {
    };
  }
}
</script>
<style lang="css" scoped>
</style>
javascript webpack babel
1个回答
1
投票
import app from './app.vue'

此行

实际上就是这个意思,它应该和import一样工作:

const app = require('./app.vue').default

为完整性起见,此行:
const app = require('./app.vue')

相当于:

import * as app from './app.vue'
© www.soinside.com 2019 - 2024. All rights reserved.