1

I'm using typescript and webpack to compile it. so I need access node fs module. in app.ts I imported it:

import fs from 'fs'

const plans = fs.readFileSync('plans.csv', {
  encoding: 'utf-8',
})

console.log(plans)

but I got this error: Module not found: Error: Can't resolve 'fs' in ...

webpack.config:

const path = require('path')

module.exports = {
  mode: 'development',
  entry: './src/app.ts',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: 'dist',
  },
  devtool: 'inline-source-map',
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.ts', '.js'],
  },
}

and package.json:

{
  "name": "name",
  "version": "1.0.0",
  "description": "description",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server",
    "build": "webpack --config webpack.config.prod.js"
  },
  "devDependencies": {
    "clean-webpack-plugin": "^3.0.0",
    "lite-server": "^2.5.4",
    "ts-loader": "^6.2.1",
    "typescript": "^3.7.2",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.9.0"
  },
  "dependencies": {}
}

i added this code to webpack.config but it didn't work:

config.node = {
  fs: 'empty',
}

any solution for access fs?

Ehsan
  • 766
  • 10
  • 17
  • 1
    Not sure why you are bothering with Webpack for a Node application. It's benefits only really hit if you're targetting a browser. I'd just use the typescript compiler directly. – Quentin Aug 23 '21 at 09:14
  • @Quentin I need fs to access and read a CSV file. do you have any alternative for fs module in this situation? – Ehsan Aug 23 '21 at 09:19
  • In what situation? Doesn't the duplicate question address how to target Node.js with Webpack in a way that supports `fs`? – Quentin Aug 23 '21 at 09:19
  • @Quentin in a situation that I'm using typescript and compile typescript with webpack. – Ehsan Aug 23 '21 at 09:21
  • Again: Is something wrong with the duplicate? – Quentin Aug 23 '21 at 09:21

0 Answers0