Fre*_*ind 5 javascript webpack shelljs
我想使用shelljs在javascript中编写一些脚本,因为我想使用一些新的JavaScript功能,所以我使用Babel + webpack将我的代码捆绑到一个bundle js中。
代码很简单:
entry.js
import shell from 'shelljs'
shell.exec('ls')
Run Code Online (Sandbox Code Playgroud)
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']
}
}]
}]
}
}
Run Code Online (Sandbox Code Playgroud)
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"
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行“ 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)
Run Code Online (Sandbox Code Playgroud)
我不知道为什么。
这也是针对此问题的完整的小型演示,您可以克隆并运行它:
https://github.com/freewind-demos/javascript-shelljs-webpack-demo
我可以通过修改我的 Webpack 配置来解决这个问题。
在撰写本文时,ShellJS 使用节点来执行名为-codeexec-child.js
的JS 文件。
问题是捆绑的代码不知道该文件在哪里,有两个原因。
您需要node: false
另外指定target: node
以避免全局模拟。这里写得很好。
您需要显式地将文件复制到输出目录,因为 __dirname 将指向那里,然后path.join(__dirname, 'exec-child.js')
才有效。您可以使用 来执行此操作copy-webpack-plugin
。这是我正在使用的配置的示例。