使用电子和网络包需要vm2

Gui*_*adi 7 javascript node.js webpack electron

当我尝试vm2使用Webpack在Electron渲染器进程中导入模块时遇到错误.

import fs from 'fs'

console.log('ok')

const { NodeVM } = require('vm2')

console.log('ko')
Run Code Online (Sandbox Code Playgroud)

这是Webpack显示的错误:

WARNING in ./~/vm2/lib/main.js
Critical dependencies:
180:26-33 require function is used in a way in which dependencies cannot be statically extracted
335:15-22 require function is used in a way in which dependencies cannot be statically extracted
367:26-33 require function is used in a way in which dependencies cannot be statically extracted
 @ ./~/vm2/lib/main.js 180:26-33 335:15-22 367:26-33

WARNING in ./~/vm2/lib/sandbox.js
Module parse failed: /Users/guillaume/Voyager/Voyager/node_modules/vm2/lib/sandbox.js 'return' outside of function (20:0)
You may need an appropriate loader to handle this file type.
SyntaxError: 'return' outside of function (20:0)
    at Parser.pp.raise (/Users/guillaume/Voyager/Voyager/node_modules/acorn/dist/acorn.js:923:13)
    at Parser.pp.parseReturnStatement (/Users/guillaume/Voyager/Voyager/node_modules/acorn/dist/acorn.js:1864:74)
Run Code Online (Sandbox Code Playgroud)

我尝试从我的webpack配置中排除node_modules文件夹:

module: {

    loaders: [{
      test: /\.js$/,
      include: PATHS.app,
      loader: 'babel',
      exclude: /node_modules/,
      query: {
        presets: [ 'es2015', 'react', 'stage-1' ],
        plugins: [ 'add-module-exports', 'transform-decorators-legacy' ],
      },
    }, {
      test: /\.scss$/,
      loaders: [ 'style', 'css', 'postcss-loader?parser=postcss-scss' ],
      include: PATHS.app,
    }],
  }
Run Code Online (Sandbox Code Playgroud)

但它似乎没有用.第一个console.log出现,而不是第二个出现.我也添加了目标webpack-target-electron-renderer.相同..

最后,当我添加时externals: [/vm2/],Webpack不会抛出任何错误,但渲染器控制台说Uncaught ReferenceError: vm2 is not defined

我猜它与动态vm2使用require和webpack不喜欢的事实有关(因为导入fs工作正常)

这个问题来自哪里,我该如何解决?