본문 바로가기
Develop/React

[error] Module not found: Error: Can't resolve 'fs' in '..../node_modules/~~~~~~~'

by 3-stack 2022. 1. 1.

[ 상황 ]

webpack3로 잘 번들링해서 사용하고 있던 react 프로젝트.

새롭게 추가할 npm을 지원하지 않는 문제 + 더 빠른 빌드 속도를 위해서 webpack5로 버전을 올렸다.

업그레이드를 하자 프로젝트를 실행(yarn start)하거나 빌드(yarn build)할 때 다음과 같은 오류가 나타났다.

Module not found: Error: Can't resolve 'fs' in '/home/adslk/bitbucket/pams_citest/pesadmin/node_modules/helpme-js/build/es6/env'

node_moduels 모듈을 사용하기 위해 reoslve를 진행하는데 'fs'를 사용할 수 없다고 한다.

 

[ 원인 ]

fs는 node에서 제공하는 기본 모듈이므로 모듈은 확실히 존재한다.

webpack5 공식문서를 보면 아래와 같이 변동됨을 확인할 수 있다.

간단히 말해 앞으로는 Node.js 코어 모듈을 자동으로 polyfill 하지 않는다는 말씀.

Webpack 5 no longer polyfills Node.js core modules automatically which means if you use them in your code running in browsers or alike, you will have to install compatible modules from npm and include them yourself. Here is a list of polyfills webpack has used before webpack 5:

 

[ 해결 ]

  • 공식문서에 따르면 아래와 같이 webpack 설정에 fallback 옵션으로 `polyfill`을 직접 설정하라고 안내한다.
    하지만 실패...
module.exports = {
  resolve: {
    fallback: {
      fs: require.resolve('fs'),
    },
  },
};

 

  • 아래와 같이 polyfill 하지 않으면 성공한다.
  • 노드 환경이 확실하니 문제되지 않지만 찝찝하면 node-polyfill-webpack-plugin 플러그인을 사용하하는 것도 방법이다.
module.exports = {
  resolve: {
    fallback: {
      fs: false
    },
  },
};

 

 

[ 번외 ]

소스코드에서 발생하는 경우는 아래와 같이 해결.

  • babel 설정 확인 - "preset": [ react-app ] 체크.
{
  "presets": ["react-app"]
}
  • eslint 설정 확인 - "node": true 옵션 체크
{
  "env": {
    "browser": true,
    "node": true,
    "es2021": true,
    "jest": true
  },
}

 

댓글