5

i have a csv file in this structure

name,year,href,src
Parasite,2019,parasite-2019,film-poster/4/2/6/4/0/6/426406-parasite-0-460-0-690-crop.jpg

i would like to import this file as a list with each line as a dict in this way:

[{'name':'Parasite','year':'2019','href':'parasite-2019','src':'film-poster/4/2/6/4/0/6/426406-parasite-0-460-0-690-crop.jpg'}]

i tried using import csv from './filmList.csv' inside the <script> tag, but that only gives me an error on load:

[plugin:vite:import-analysis] Failed to parse source for import analysis because the content contains invalid JS syntax. You may need to install appropriate plugins to handle the .csv file format.

1 Answer 1

7

Install @rollup/plugin-dsv as a dev dependency:

npm i -D @rollup/plugin-dsv

...and configure Vite to use it:

// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import dsv from '@rollup/plugin-dsv' 👈

export default defineConfig({
  plugins: [
    vue(),
    dsv(), 👈
  ],
})

Then importing a .csv file would produce the object array, as you were expecting:

<script>
// MyComponent.vue
import csv from './filmList.csv'
console.log(csv) // => [{'name':'Parasite','year':'2019','href':'parasite-2019','src':'film-poster/4/2/6/4/0/6/426406-parasite-0-460-0-690-crop.jpg'}]
</script>

demo

Sign up to request clarification or add additional context in comments.

1 Comment

I spent a few hours trying to understand, so if it may help someone else, using it with TypeScript, you need to add these lines in your .d.ts file: ``` declare module "*.csv" { export default <{ [key: string]: any }>Array; } ```

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.