首页 > 解决方案 > 导入有效,但为什么要求不起作用?

问题描述

我正在使用 webpack 构建一个简单的项目,在main.js. 如果我使用importto import app.js,结果效果很好。但是,如果我使用requirevue 模板将不会显示在页面上。

我以为 Babel 编译importrequire; 如果是这样,为什么require不在这里工作?

使用 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>

索引.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'
    }
  },
};

应用程序.js

<template>
<div class="app-contianer">
    <h1>test</h1>
</div>
</template>
<script>
export default {
  data () {
    return {
    };
  }
}
</script>
<style lang="css" scoped>
</style>

标签: javascriptwebpackbabeljs

解决方案


require并且import在访问导入对象的方式上有所不同。

import app from './app.vue'

这条线实际上是这个意思,这应该和下面的一样import

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

为了完整起见,这一行:

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

相当于:

import * as app from './app.vue'

推荐阅读