javascript - 导入有效,但为什么要求不起作用?
问题描述
我正在使用 webpack 构建一个简单的项目,在main.js
. 如果我使用import
to import app.js
,结果效果很好。但是,如果我使用require
vue 模板将不会显示在页面上。
我以为 Babel 编译import
到require
; 如果是这样,为什么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>
解决方案
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'
推荐阅读
- c# - 需要帮助为 UWP 创建登录系统
- c++ - 将 Ref 对象作为类成员
- php - 保持在循环中减去值得到mysql结果php
- ruby-on-rails - 如何仅将 link_to 应用于 content_tag 中的部分文本?
- task - 气流任务失败,没有空日志并且不发送电子邮件
- qt - 如何在可执行文件附近安装 qt 库
- javascript - 从 angularjs 控制器替换 url 栏中的现有 url
- spring-boot - 如何对发布请求进行 LDAP 身份验证
- sas - SAS Line graphs from Data in a row rather than column
- python - Python OpenAI's gym Error (AttributeError: 'Timer' object has no attribute '_seed')