Webpack: use data from parent directory without copying

Viewed 370

I have a project folder structured like this:

project-name/   
  data/
   data.csv
  dist/
   index.js
  src/
   index.js

And want a remote directory like this:

project-name/   
  data/
   data.csv
  dist/
   index.js
    > `doSomething("../data/data.csv")`

How do I make this work in both webpack-dev-server and in the production path? If I use copywebpack plugin, then the data goes inside the dist/, which I don't want. But if I use a relative directory without copying the data, then the build fails.

4 Answers

Actually, you should use Webpack csv-loader in your Webpack configuration file like below:

module: {
  rules: [
    {
      test: /\.csv$/,
      loader: 'csv-loader',
      options: {
      dynamicTyping: true,
        header: true,
        skipEmptyLines: true,
      },
    },
  ],
},

And then use it inside your code like below:

import csvPath from './project-name/data/foo.csv'

Can you use an alias?

webpack.config.js:

  const path = require("path");

  module.exports = {
  ...

    resolve: {
      alias: {
        Data: path.resolve(__dirname, "./project-name/data/"),
      },
    },
  }

src/index.js:

  import data from "Data/data.csv"

Have you tried excluding it in the test? Something like this:

   {
    entry: "./src/index.js",
    module: {
      rules: [
        {
          test: /\.js$/,
          use: ["babel-loader or whatever loader you use"],
        },
        {
          test: /\.csv$/,
          exclude: ["./data/"],
        },
      ],
    },
    output: {
      filename: "index.js",
      path: path.resolve(__dirname, "dist"),
    },
   },

There is a similar question on how to not bundle files in webpack here

You can use context param.

    new CopyWebpackPlugin(
    [{
        context: './source/',
        from: '**/*.html',
        to: './public',
        force: true
    }], {
        copyUnmodified: true
    }
)
Related