前端 JS 经典:读取文件原始内容

前言:有些时候在工程化开发中,我们需要读取文件里面的原始内容,比如,你有一个文件,后缀名为 .myfile,你需要拿到这个文件里的内容,该怎么处理呢。

在 vue2 中,因为 vue2 使用 vue-cli 脚手架,构建工具用的 webpack。然后对不同后缀的解析使用的不同 load,我们自己定义的后缀文件 .myfile,webpack 不知道需要用什么 load 去解析它,所以我们需要在 vue.config.js 里面配置。

在组件中导入 .myfile 文件:

html 复制代码
<template>
  <div>{{ myfile }}</div>
</template>

<script>
  import myfile from "./xx.myfile";
  export default {
    data() {
      return {
        myfile,
      };
    },
  };
</script>

vue.config.js 配置 load 解析后缀名为 .myfile,raw-load 专门用来拿原始内容的。

javascript 复制代码
const { defineConfig } = require("@vue/cli-service");

module.exports = defineConfig({
  configureWebpack: {
    module: {
      rules: {
        text: /\.myfile$/,
        loader: "raw-loader",
      },
    },
  },
});

在 vue3 中就很简单了,直接给导入的文件加入后缀就可以:

html 复制代码
<template>
  <div>{{ myfile }}</div>
</template>

<script setup>
  import myfile from "./xx.myfile?raw";
</script>
相关推荐
小小测试开发4 小时前
安装 Python 3.10+
开发语言·人工智能·python
KaMeidebaby5 小时前
卡梅德生物技术快报|PD1 单克隆抗体定制配套 N 糖全谱质控开发
前端·人工智能·算法·数据挖掘·数据分析
nuIl6 小时前
实现一个 Coding Agent(3):工具调用
前端·agent·cursor
nuIl6 小时前
实现一个 Coding Agent(4):ReAct 循环
前端·agent·cursor
AAA大运重卡何师傅(专跑国道)6 小时前
【无标题】
开发语言·c#
nuIl6 小时前
实现一个 Coding Agent(1):一次 LLM 调用
前端·agent·cursor
nuIl6 小时前
实现一个 Coding Agent(2):让 LLM 流式响应
前端·agent·cursor
copyer_xyf6 小时前
Python 异常处理
前端·后端·python
sugar__salt6 小时前
从栈队列数据结构到JS原型面向对象全解
前端·javascript·数据结构
XBodhi.6 小时前
Visual Studio C++ 语法错误: 缺少“;”(在“return”的前面)
开发语言·c++·visual studio