Problem
I know that ES6 imports
and NODE require()
use static analysis and do not support dynamic paths. But how do we work around it? What's the solution?
My Electron app, during installation copies shortcuts.js
file from development (project) folder [project_dir]/public/resources
into the [app_installation_dir]/resources
folder.
So the problem is:
- In development the app should import
../public/resources/shortcuts.js
- In production the app should import
[app_installation_dir]/resources/shortcuts.js
I cannot specify the "non-dynamic" path for production since I don't know in advance what [app_installation_dir]
path is going to be.
Code
I tried the following, but expectedly only the else
brunch works:
const shortcuts = process.env.NODE_ENV === 'production'
? require(`${process.resourcesPath}/shortcuts.js`).data
: require(../public/resources/shortcuts.js`).data
After installing the app, in production, I'm getting the error:
Uncaught Error: Cannot find module [app_installation_dir]/resources/shortcuts.js
since, I guess, require
doesn't see the dynamic path as something it can import (I checked, the file exists at this path).
I then converted the file from module.exports
to export default {}
and tried the following ES6 method but I get the same error:
if (process.env.NODE_ENV === 'production') {
const importPath = path.join(process.resourcesPath, 'shortcuts.js')
import(importPath)
.then((data) => {
console.log('IMPORT DATA', data)
})
}
else if (process.env.NODE_ENV === 'development') {
import('../public/resources/shortcuts.js')
.then((data) => {
console.log('IMPORT DATA', data)
})
}
babel.config.js
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset',
]
}
Project created
vue create app-name
> selected [babel, eslint]
vue add electron-builder