You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将静态文件内容作为字符串导入?替代已弃用的raw-loader

替代raw-loader:现代构建工具导入文本文件为字符串的方案

之前依赖的raw-loader已被弃用,目前主流现代构建工具都有内置或官方推荐的替代方案,分工具说明如下:

Webpack 5+

Webpack 5原生支持资源模块,无需额外安装loader:

全局配置(自动处理所有.txt文件)

在webpack.config.js中添加规则:

module.exports = {
  module: {
    rules: [
      {
        test: /\.txt$/i,
        type: 'asset/source', // 将文件内容导出为字符串
      },
    ],
  },
};

之后直接导入使用:

// code.js
import res from './res.txt';
console.log(res); // 输出文件完整内容

按需导入(无需全局配置)

导入时通过资源查询断言指定处理方式:

import res from './res.txt?raw';

Vite

Vite原生支持文本文件导入,两种方式:

按需导入

直接在导入路径后加?raw后缀:

// code.js
import res from './res.txt?raw';
console.log(res);

全局默认处理

如果希望所有.txt文件默认被当作字符串导入,在vite.config.js中配置:

import { defineConfig } from 'vite';

export default defineConfig({
  optimizeDeps: {
    esbuildOptions: {
      loader: {
        '.txt': 'text',
      },
    },
  },
});

之后可直接import res from './res.txt';

Rollup

使用官方插件@rollup/plugin-text实现:

  1. 安装插件
npm install @rollup/plugin-text --save-dev
  1. 配置rollup.config.js
import text from '@rollup/plugin-text';

export default {
  input: 'code.js',
  output: {
    file: 'bundle.js',
    format: 'esm',
  },
  plugins: [text({ include: '**/*.txt' })], // 指定要处理的文件
};
  1. 导入使用
// code.js
import res from './res.txt';
console.log(res);

内容的提问来源于stack exchange,提问作者SRobertJames

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 14:52:36