如何在Nuxt(或Vue)中以字符串形式从文本文件中读取内容?

sam*_*m k 2 vue-component vuejs2 nuxt.js

我想阅读我在.vue文件中导入的文本文件的内容,例如import ToS from '~/static/terms-of-service.txt';

我想以字符串形式访问内容。

我该怎么做?

Roc*_*coB 10

我正在使用 nuxt(使用 vue cli 3 创建),这对我有用:

  1. npm install --save-dev raw-loader
  2. 更新 nuxt.config.js
  build: {
    /*
    ** You can extend webpack config here
    */
    extend (config, ctx) {

      config.module.rules.push({
        enforce: 'pre',
        test: /\.txt$/,
        loader: 'raw-loader',
        exclude: /(node_modules)/
      });

    }
  }
Run Code Online (Sandbox Code Playgroud)


Ham*_*son 6

VUE CLI 3

  1. 首先安装原始加载程序 npm install raw-loader --save-dev

  2. 如果您没有vue.config.js,请在根目录下创建一个并添加

    module.exports = {
      chainWebpack: config => {
        config.module
          .rule('raw')
          .test(/\.txt$/)
          .use('raw-loader')
          .loader('raw-loader')
          .end()
      }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 要以字符串形式获取文本文件(如果放置在src / assets / txt /中): import file from '@/assets/txt/file.txt'

注意:请记住要重建


sam*_*m k 1

我最终使用了https://github.com/webpack-contrib/raw-loader

看来vue中需要一个loader来读取文件