我希望使用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