Reputation: 1039
I have an electron app that needs to read a file stored in %appdata%
(or the equivalent for macOS and linux). I am importing the file like this
const appPath = app.getPath("appData");
const data = await import(appPath + "/app/file.json");
If I run the code from the source file it works, but when I am trying to bundle it with webpack, I get a Module not found
error. I know this is caused by webpack trying to perform an analysis on my imports.
So is there a way to import a file dynamically in webpack?
Thanks in advance!
Edit: my webpack config (no babel since I am using typescript)
var path = require("path");
const CopyPlugin = require('copy-webpack-plugin');
var nodeExternals = require('webpack-node-externals');
module.exports = {
mode: 'production',
entry: "./src/index.ts",
externals: [nodeExternals()],
output: {
filename: "main.js",
path: path.resolve(__dirname, 'build')
},
node:{
__dirname:false
},
target: "electron-main",
resolve: {
alias: {
['firebase/app']: path.resolve(__dirname, 'node_modules/firebase/app/dist/index.cjs.js'),
['firebase']: path.resolve(__dirname, 'node_modules/firebase/dist/index.node.cjs.js')
}, extensions: ['.ts', '.js']
},
module: {
noParse: "/public/**/*",
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
// {
// test: /\.json$/,
// loader: 'json-loader'
// }
],
},
plugins: [
new CopyPlugin([
{ from: './src/public', to: './public' }
]),
]
}
Upvotes: 3
Views: 429
Reputation: 156
I guess you can't, but the NormalModuleRpelacementPlugin
might be a solution for your problem. You can use it in build time, however it could depends the environment for example.
The file path is same in the code, but after the build it will be changed whatever you want.
https://webpack.js.org/plugins/normal-module-replacement-plugin/
Upvotes: 0
Reputation: 4901
By looking into documentation it seems the answer is in Module Methods section:
Dynamic expressions in import()
It is not possible to use a fully dynamic import statement, such as
import(foo)
. Becausefoo
could potentially be any path to any file in your system or project.The
import()
must contain at least some information about where the module is located. [...]
It is not clear if you need to read it at build time or at runtime, if its the former then make sure to copy the file to working directory (so that file is bundled in the build), if its the latter then you could use fs
module to get the file at runtime.
Upvotes: 2
Reputation: 20132
Maybe you can try dynamic import and use promises like this
import(appPath + "/app/file.json").then(data => {
console.log(data)
});
Upvotes: 0