前言:有些時候在工程化開發中,我們需要讀取文件里面的原始內容,比如,你有一個文件,后綴名為 .myfile,你需要拿到這個文件里的內容,該怎么處理呢。
在 vue2 中,因為 vue2 使用 vue-cli 腳手架,構建工具用的 webpack。然后對不同后綴的解析使用的不同 load,我們自己定義的后綴文件 .myfile,webpack 不知道需要用什么 load 去解析它,所以我們需要在 vue.config.js 里面配置。
在組件中導入 .myfile 文件:
<template><div>{{ myfile }}</div>
</template><script>import myfile from "./xx.myfile";export default {data() {return {myfile,};},};
</script>
vue.config.js 配置 load 解析后綴名為 .myfile,raw-load 專門用來拿原始內容的。
const { defineConfig } = require("@vue/cli-service");module.exports = defineConfig({configureWebpack: {module: {rules: {text: /\.myfile$/,loader: "raw-loader",},},},
});
?在 vue3 中就很簡單了,直接給導入的文件加入后綴就可以:
<template><div>{{ myfile }}</div>
</template><script setup>import myfile from "./xx.myfile?raw";
</script>