Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack import from %appdata%

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' }
        ]),
    ]
 }
like image 706
Adrian Pascu Avatar asked Mar 01 '26 10:03

Adrian Pascu


1 Answers

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). Because foo 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.

like image 78
Ivar Avatar answered Mar 03 '26 23:03

Ivar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!