我想使用shelljs在javascript中编写一些脚本,因为我想使用一些新的JavaScript功能,所以我使用Babel + webpack将我的代码捆绑到一个捆绑的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
答案 0 :(得分:1)
我能够通过修改Webpack配置来解决此问题。
ShellJS使用节点执行名为exec-child.js
-code at the time of writing的JS文件。
问题在于捆绑的代码不知道该文件在哪里,有两个原因。