webpack + shelljs 会抛出 "Error: Cannot find module '/exec-child.js'" 的错误信息。

9

我希望使用shelljs来编写一些JavaScript脚本,因为我想使用一些新的JavaScript功能,所以我使用了Babel+webpack将我的代码打包成一个单独的bundle js。

代码非常简单:

entry.js

import shell from 'shelljs'

shell.exec('ls')

webpack.conf.js

module.exports = {
    mode: "development",
    target: 'node',
    entry: './entry.js',
    output: {
        path: __dirname,
        filename: './dist/bundle.js'
    },
    module: {
        rules: [{
            test: /\.js$/,
            use: [{
                loader: 'babel-loader', options: {
                    presets: ['@babel/preset-env']
                }
            }]
        }]
    }
}

package.json

{
  "scripts": {
    "demo": "webpack && node ./dist/bundle.js"
  },
  "devDependencies": {
    "@babel/core": "7.2.2",
    "@babel/preset-env": "7.4.2",
    "babel-loader": "8.0.6",
    "webpack": "4.28.1",
    "webpack-cli": "3.2.1"
  },
  "dependencies": {
    "shelljs": "0.8.3"
  }
}

当我运行“npm install && npm run demo”时,它会抛出以下错误:
Error: Cannot find module '/exec-child.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
webpack:///./node_modules/shelljs/src/common.js?:412
        throw e;
        ^

ShellJSInternalError: ENOENT: no such file or directory, open '/var/folders/gm/t8kf08qn0598qcl_vkxxyhxc0000gr/T/shelljs_d7da547d2136239bb317'
    at Object.openSync (fs.js:443:3)
    at Object.readFileSync (fs.js:343:35)
    at execSync (webpack:///./node_modules/shelljs/src/exec.js?:85:17)
    at Object._exec (webpack:///./node_modules/shelljs/src/exec.js?:213:12)
    at Object.eval [as exec] (webpack:///./node_modules/shelljs/src/common.js?:348:23)
    at eval (webpack:///./entry.js?:5:48)

我无法理解其中的原因。

下面是一个关于这个问题的完整小型演示,你可以直接克隆并运行:

https://github.com/freewind-demos/javascript-shelljs-webpack-demo


我已经将问题缩小到了 shelljs/src/exec.js 中的第 54 行。 - Prichmp
我认为这是同样的问题:https://github.com/shelljs/shelljs/issues/956 - Prichmp
1个回答

2

我通过修改Webpack配置成功解决了这个问题。

ShellJS使用node来执行一个名为exec-child.js的JS文件 - 在写作时的代码

问题在于,打包后的代码不知道该文件在哪里,原因有两个。

  1. 您需要除了target: node之外还要指定node: false来避免全局模拟。 在这里有一个很好的解释。

  2. 您需要显式地将文件复制到输出目录,因为__dirname将指向那里,然后path.join(__dirname, 'exec-child.js')将是有效的。您可以使用copy-webpack-plugin来实现这一点。这是我的配置的一个示例


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接