vue项目中导入本地pdf文件 [英] Import a local pdf file in vue project
问题描述
我正在尝试在我的 vue 项目中导入本地 pdf 文件(使用 vue-cli@latest 引导,使用默认配置)但 vue 尝试解析它并给出此错误:
./src/assets/myFile.pdf 1:0模块解析失败:意外令牌 (1:0)您可能需要一个合适的加载器来处理这种文件类型.(此二进制文件省略了源代码)
我只想通过单击按钮使文件可供下载,因此我不需要解析它,但我需要它通过 webpack 以便文件名获得哈希值,因此我想避免将其放入public 文件夹并使用 env.BASE_URL
.
这里是组件的我的 .vue
文件.
<div class="root"></模板><脚本>从'../assets/my.pdf'导入MyPdf;导出默认{name: "PDF下载",数据:函数(){返回 { MyPdf }}}<样式范围>...</风格>
我在 SO 上发现了类似的问题,但没有一个答案能解决问题.我发现的唯一解决方案是在 vue 文档上使用 public
文件夹,但我不想要那个,因为我想要文件名中的哈希值.我是 vue 新手,我来自 React,在 React 中你可以简单地在 js 中导入一个 pdf、word 等文件,并在 a
和用户的 href
中使用它可以查看/下载.
您不必导入它.只需创建一个 <a>
标签,并为您的 pdf 文件提供正确的 URL.之前可以直接在浏览器中查看路径是否正确下载.
如果您遇到同样的问题并且正在使用 webpack,则必须确保您使用的是 pdf
扩展的加载器.在这种情况下,用户使用的是 vue-cli,而更改 webpack 配置的方法是在 vue.config.js
上.我创建了一个 gist 来展示如何添加它.
I am trying to import a local pdf file in my vue project (bootstrapped using vue-cli@latest, using default config) but vue tries to parse it and gives this error:
./src/assets/myFile.pdf 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
I just want to make the file available for download from a button click so I don't need to parse it but I need it to go through webpack so that the filename will get hashes, hence I want to avoid putting it in public folder and use env.BASE_URL
.
Here the my .vue
file for the component.
<template>
<div class="root">
<a
v-bind:href="MyPdf"
download='Something.pdf'
>
Download as pdf
</a>
</div>
</template>
<script>
import MyPdf from '../assets/my.pdf';
export default {
name: "PdfDownload",
data: function () {
return { MyPdf }
}
}
</script>
<style scoped>
...
</style>
I found similar questions on SO, but none of the answers solve the problem. I only solution I found was on vue docs to use public
folder but I don't want that because I want hashes in filename. I am new to vue, I come from React, and in React you can simply import a pdf, word etc. file in js and use it in href
of a
and users can view/download it.
You don't have to import it. Just create a <a>
tag with correct URL to your pdf file.
You can check if the path is correct downloading directly in the browser before.
Edit:
In case you are facing the same problem and you are using webpack, you have to make sure you are using a loader for the pdf
extension. In this case, the user was using vue-cli, and the way to change webpack config is on vue.config.js
. I created a gist to show how add it.
这篇关于vue项目中导入本地pdf文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!