Search code examples
webpackelectron-forge

Dynamic imports in Electron commonjs with Typescript and Webpack


I want to dynamically import js files in the 'back-end'/nodejs side of an Electron app (so not on the 'renderer' side) in a Electron Forge v6.2.1 project build with the Webpack + Typescript template project.

These are like plugins that can change all the time and cannot be part of the webpack build.

My code now looks like this:

// note the forward slashes!
const cntntFile = "C:/Users/Sander/Documents/.../plugin01.js";

console.log('\n----------\ncntntFile: ' + cntntFile + '\n---------\n');

const cntnt: any = 
  await import( /* webpackIgnore: true */  cntntFile )
    .then(res => { console.log('\nResult ===================\n', res) })
    .catch(err => { console.log('\nError =============\n', err) })
;

What i get is:

Error =============
 Error: Cannot find module 'C:/Users/Sander/Documents/.../plugin01.js'
    at webpackEmptyContext (C:\Users\Sander\Documents\...\.webpack\main\index.js:65578:10)
    at C:\Users\Sander\Documents\...\.webpack\main\index.js:65375:130
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 'MODULE_NOT_FOUND'
}

I can Ctrl+Click the path of the module in VSCode and it just simply opens the file, so I know the path is correct.

When I Ctrl+Click the second error (65375:130), i can see this:

const cntnt = yield Promise.resolve().then(() => __importStar(__webpack_require__("./src/tan/oracle sync recursive")(cntntFile)))
.then(res => { console.log('\nResult ===================\n', res) })
.catch(err => { console.log('\nError ==================\n', err) });

So it seems to me that because of __webpack_require__( it's not working.

I tried several things but can not get it to work. Some attempts:

  • changes tsconfig.json to not remove comments
  • did this /*! /* webpackIgnore: true */ as described here: [Support /** webpackIgnore: true */ #1256][1]

At some time I read "webpackIgnore is only for import() not for require", but later on I read this was added for require as well.

How to make this work?


Solution

  • As I found out here: webpack native require doesn't work in windows #15975 You have to enable magic comments first!

    it was disable[d] by default due perf reasons

    So:

    // file: webpack.main.config.ts
      ...
    
      // Put your normal webpack config below here
      module: {
        rules,
        parser: {
          javascript: {
            commonjsMagicComments: true,        <-- added
            importMeta: false,
          }
        }
      },
      resolve: {
    
      ...