Webpack can not use __dirname?

2020-04-04 04:04发布

I am trying to use node-postgres to hook my app up to Postgres. The code I use is:

import React from 'react';
import pg from 'pg';
import fs from 'fs';
var cn = {
  host: 'localhost', // server name or IP address; 
  port: 5432,
  database: 'my_db',
  user: 'myname',
  password: 'mypass'
};

and it produces the error:

index.js:5 Uncaught ReferenceError: __dirname is not defined
up  @ index.js:5
__webpack_require__ @ bootstrap 539ecc7…:19
(anonymous function)  @ client.js:4
__webpack_require__ @ bootstrap 539ecc7…:19
(anonymous function)  @ index.js:3
console.EventEmitter._events  @ index.js:81
__webpack_require__ @ bootstrap 539ecc7…:19
(anonymous function)  @ app.js:26957
__webpack_require__ @ bootstrap 539ecc7…:19
content @ bootstrap 539ecc7…:39
__webpack_require__ @ bootstrap 539ecc7…:19
(anonymous function)  @ bootstrap 539ecc7…:39
(anonymous function)  @ bootstrap 539ecc7…:39
webpackUniversalModuleDefinition  @ universalModuleDefinition:7
(anonymous function)  @ universalModuleDefinition:10

The path on index.js provided in the console is webpack:///./~/pg/~/pgpass/lib/index.js:5

I tried @Renzo Poddighe solution at how to write file with node webkit js? but I still get the same error. I think it may have something to do with the discussions at https://github.com/nwjs/nw.js/wiki/Differences-of-JavaScript-contexts#resolving-relative-paths-to-other-scripts and https://github.com/nwjs/nw.js/issues/264. They say that

// __dirname is not defined in webkit context, this is only node.js thing
console.log(__dirname); // undefined

and

__dirname works in Node.js modules, i.e. in JavaScript code that was called with require(). __dirname doesn't work only in WebKit scripts, i.e. in JavaScript code that was called with HTML , or jQuery's $.getScript(), or any other similar method.

Any ideas? Let me know what other information I need to include.

edit

I think my target is

var config = {
  entry: { app: './src/index.jsx'},
  output: {
     libraryTarget: 'umd',
     path: path.join(__dirname, 'dist'),
     filename: '[name].js'
  }, ...

My webpack.config.js looks like:

...
  node: {
    console: true,
    __dirname: true,
    dns: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
  }
...

1条回答
\"骚年 ilove
2楼-- · 2020-04-04 04:29

In that case, add this to your webpack config:

{
  node: {
    __dirname: true
  }
}

This will tell webpack to replace __dirname instances with the path of the module. This path relative to context

查看更多
登录 后发表回答