通过webpack运行脚本后无法运行脚本。 (错误:无法找到全局对象)

时间:2018-11-20 12:49:06

标签: node.js webpack

我有一个简单的脚本。

脚本/src/index.js

var fetch = require('node-fetch');

console.log("working!")
...

exports = { createClient, createDevice };

脚本/webpack.config.js

const path = require('path');

module.exports = {
    entry: './src/index.js',
    mode: 'development',
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist')
    }
};

script / package.json

{
    "name": "client",
    "version": "1.0.0",
    "private": true,
    "dependencies": {
        "node-fetch": "^2.3.0"
    },
    "devDependencies": {
        "webpack": "^4.26.0",
        "webpack-cli": "^3.1.2"
    },
    "scripts": {
        "build": "webpack"
    }
}

运行源代码工作正常

node script/src/index.js
working!

现在我想将源代码与npm依赖项捆绑在一起,以便运行

npm run build

然后我尝试运行构建的代码

node script/dist/main.js
webpack:///./node_modules/node-fetch/browser.js?:11
    throw new Error('unable to locate global object');
    ^

Error: unable to locate global object
    at getGlobal (webpack:///./node_modules/node-fetch/browser.js?:11:8)
    at eval (webpack:///./node_modules/node-fetch/browser.js?:14:14)
    at Object../node_modules/node-fetch/browser.js (/Users/xp025106/Dev/client-js/client/dist/main.js:97:1)
    at __webpack_require__ (/Users/xp025106/Dev/client-js/client/dist/main.js:20:30)
    at eval (webpack:///./src/index.js?:1:13)
    at Object../src/index.js (/Users/xp025106/Dev/client-js/client/dist/main.js:108:1)
    at __webpack_require__ (/Users/xp025106/Dev/client-js/client/dist/main.js:20:30)
    at /Users/xp025106/Dev/client-js/client/dist/main.js:84:18
    at Object.<anonymous> (/Users/xp025106/Dev/client-js/client/dist/main.js:87:10)
    at Module._compile (module.js:652:30)

为什么我不能以与运行源代码相同的方式运行构建的代码?

0 个答案:

没有答案