0%

electron vue에서 Module not found: Error: Can't resolve 'os' 에러 문제 해결

발생한 문제

electron vue 에서 개발을 하다 아래 에러가 발생하면서 실행이 되지않는 문제가 발생하였다.

1
2
3
4
5
6
7
8
9
10
Module not found: Error: Can't resolve 'os' in 'C:\Users\User\workspace\~'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "os": require.resolve("os-browserify/browser") }'
- install 'os-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "os": false }

해결방법

프로젝트 메인 폴더에 있는 vue.config.js 파일의 configureWebPack쪽에 아래 내용을 적어준다.

1
target:'electron-renderer'

위 내용을 적용하면 vue.config.js 파일의 내용은 아래와 같다.

1
2
3
4
5
6
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
configureWebpack: {
target:'electron-renderer'
}
})

만일 위와 같이 조치했는데, 아래와같은 에러가 runtime시점에 난다면 추가적인 해결책이 필요하다.

Uncaught ReferenceError: require is not defined

이미지

프로젝트 폴더 > src> background.js에서

BrowserWindow 생성시 WebPreferences의 property값을 아래처럼 입력한다.

1
2
3
4
5
6
7
8
async function createWindow() {
// Create the browser window.
const win = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true,
});

전체 코드는 아래와같다.

이미지

문제해결과정

문제를 해결하라면  install ‘os-browserify’ 을 하라고 해서 아래와 같이 yarn 을 사용하여 추가해보았다.

1
yarn add os-browserify --save

그러나 해결이 되지않았다.

구글링을 해보았다. 검색어는 : electron Error: Can’t resolve ‘os’

구글링을 해보니 똑같은 내용은 안나왔지만, 아래와 같은 내용이 stackoverflow에서 검색되었다.
Electron and TypeScript: ‘fs’ can’t be resolved

https://stackoverflow.com/questions/48476061/electron-and-typescript-fs-cant-be-resolved

os 모듈과 fs모듈은 먼가 pc의 자원을 직접적으로 사용하는 공통점이 있을테니,

동일한 해결방법을 시도해보면 해결될수도 있지 않을까란 생각이 들었다.

내용은 webpack.config.json 에 아래 내용을 넣으라는 답변이었다.

1
2
3
{
target: 'electron-renderer'
}

하지만 내 프로젝트에는 webpack.config.json이 없었다.

그냥 빈파일로 webpack.config.json 만들어서 해당 내용 넣고 실행해보았으나 실패..

vue프로젝트라면 뭔가 webpack설정을 따로해야하는지 찾아보았다.

구글링 검색어는 : vue3 webpack.config.json

그래서 나온 결과는 아래 주소였다.
https://cli.vuejs.org/guide/webpack.html#simple-configuration

vue.config.js 파일에서 configureWebpack 값을 바꿔주면 된다는내용이다.

앞선내용들을 적용하면 vue.config.js 파일의 내용을 아래와 같이 수정한다.

1
2
3
4
5
6
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
configureWebpack: {
target:'electron-renderer'
}
})