简体   繁体   English

webpack-dev-server npm运行dev引发TypeError:无法设置未定义的属性“端口”

[英]webpack-dev-server npm run dev throwing TypeError: Cannot set property 'port' of undefined

I'm running node v10.15.1, vue js, vue-cli and vue-loader with webpack, http-proxy-middleware (included) on a local win10 x64 remote host. 我正在本地win10 x64远程主机上使用webpack,http-proxy-middleware(包括)运行节点v10.15.1,vue js,vue-cli和vue-loader。 Additionally I installed and imported bootstrap v4 and bootstrap-vue successfully. 另外,我成功安装并导入了bootstrap v4和bootstrap-vue。

When I now run npm run dev it throws me the following error: 当我现在运行npm run dev它会引发以下错误:

C:\Users\Rober\dev@localhost\www\uls>npm run dev

> ulsvr@1.0.0 dev C:\Users\Rober\dev@localhost\www\uls
> webpack-dev-server --inline --progress --config build/webpack.dev.conf.js

C:\Users\Rober\dev@localhost\www\uls\build\webpack.dev.conf.js:82
      devWebpackConfig.devServer.port = port
                                      ^

TypeError: Cannot set property 'port' of undefined
    at portfinder.getPort (C:\Users\Rober\dev@localhost\www\uls\build\webpack.dev.conf.js:82:39)
    at C:\Users\Rober\dev@localhost\www\uls\node_modules\portfinder\lib\portfinder.js:190:16
    at C:\Users\Rober\dev@localhost\www\uls\node_modules\portfinder\node_modules\async\lib\async.js:52:16
    at C:\Users\Rober\dev@localhost\www\uls\node_modules\portfinder\node_modules\async\lib\async.js:269:32
    at C:\Users\Rober\dev@localhost\www\uls\node_modules\portfinder\node_modules\async\lib\async.js:44:16
    at C:\Users\Rober\dev@localhost\www\uls\node_modules\portfinder\lib\portfinder.js:151:16
    at Server.onListen (C:\Users\Rober\dev@localhost\www\uls\node_modules\portfinder\lib\portfinder.js:43:7)
    at Object.onceWrapper (events.js:277:13)
    at Server.emit (events.js:189:13)
    at emitListeningNT (net.js:1311:10)
    at process._tickCallback (internal/process/next_tick.js:63:19)
    at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! ulsvr@1.0.0 dev: `webpack-dev-server --inline --progress --config build/webpack.dev.conf.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ulsvr@1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Rober\AppData\Roaming\npm-cache\_logs\2019-03-03T07_27_56_266Z-debug.log

Here is my package.json which can be found in my project {root}=> 这是我的package.json ,可以在我的项目{root} =>中找到

(C:\\Users\\Rober\\dev@localhost\\www\\uls)\u003c/i> (C:\\ Users \\ Rober \\ dev @ localhost \\ www \\ uls)

:

{
  "name": "ulsvr",
  "version": "1.0.0",
  "private": true,
  "description": "A Vue.js project",
  "author": "",
  "scripts": {
    "build": "node build/build.js",
    "lint": "vue-cli-service lint",
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
    "rest": "start restart_server.bat",
    "start": "npm run dev",
    "stop": "taskkill /f /im node.exe"
  },
  "dependencies": {
    "@vue/cli-service": "^3.4.1",
    "ajv": "^6.9.2",
    "bootstrap": "^4.3.1",
    "bootstrap-vue": "^2.0.0-rc.13",
    "jquery": "^3.3.1",
    "vue": "^2.6.8",
    "webpack-hot-middleware": "^2.24.3"
  },
  "devDependencies": {
    "@vue/cli-plugin-eslint": "^3.4.1",
    "@vue/eslint-config-standard": "^4.0.0",
    "autoprefixer": "^9.4.9",
    "babel-core": "^6.22.1",
    "babel-eslint": "^10.0.1",
    "babel-helper-vue-jsx-merge-props": "^2.0.3",
    "babel-loader": "^8.0.5",
    "babel-plugin-syntax-jsx": "^6.18.0",
    "babel-plugin-transform-runtime": "^6.22.0",
    "babel-plugin-transform-vue-jsx": "^3.5.0",
    "babel-preset-env": "^1.3.2",
    "babel-preset-stage-2": "^6.22.0",
    "chalk": "^2.0.1",
    "copy-webpack-plugin": "^5.0.0",
    "css-loader": "^2.1.0",
    "eslint": "^5.8.0",
    "eslint-plugin-vue": "^5.0.0",
    "extract-text-webpack-plugin": "^3.0.0",
    "file-loader": "^3.0.1",
    "friendly-errors-webpack-plugin": "^1.6.1",
    "html-webpack-plugin": "^3.2.0",
    "http-proxy-middleware": "^0.19.1",
    "node-notifier": "^5.1.2",
    "optimize-css-assets-webpack-plugin": "^5.0.1",
    "ora": "^3.2.0",
    "portfinder": "^1.0.13",
    "postcss-import": "^12.0.1",
    "postcss-loader": "^3.0.0",
    "postcss-url": "^8.0.0",
    "rimraf": "^2.6.0",
    "semver": "^5.3.0",
    "shelljs": "^0.8.3",
    "uglifyjs-webpack-plugin": "^2.1.2",
    "url-loader": "^1.1.2",
    "vue-loader": "^15.7.0",
    "vue-style-loader": "^4.1.2",
    "vue-template-compiler": "^2.6.8",
    "webpack": "^4.29.6",
    "webpack-bundle-analyzer": "^3.1.0",
    "webpack-chain": "^5.2.0",
    "webpack-cli": "^3.2.3",
    "webpack-dev-server": "^3.2.1",
    "webpack-merge": "^4.1.0"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 8"
  ],
  "engines": {
    "node": ">= 6.0.0",
    "npm": ">= 3.0.0"
  }
}

I guess the issue is somehow related to some packages being unable to interact properly due to mismatch in version. 我猜这个问题与某些软件包由于版本不匹配而无法正确交互有关。 Though it could also be a misconfiguration. 虽然这也可能是一个错误的配置。 I'm kinda new to all of this, but I'm willing to learn. 我对所有这些都有点陌生,但我愿意学习。

Next there is my webpack configuration 接下来是我的webpack配置

{root}/build/ webpack.base.conf.js {root} / build / webpack.base.conf.js

'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}

module.exports = {
  context: path.resolve(__dirname, '../'),
  entry: {
    app: './src/main.js'
  },
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src')
    }
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
  node: {
    // prevent webpack from injecting useless setImmediate polyfill because Vue
    // source contains it (although only uses it if it's native).
    setImmediate: false,
    // prevent webpack from injecting mocks to Node native modules
    // that does not make sense for the client
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  }
}

And my problem child {root}/build/ webpack.dev.conf.js 而我的问题孩子{root} / build / webpack.dev.conf.js

'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')

const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)

const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }),
    // cheap-module-eval-source-map is faster for development
    devtool: config.dev.devtool,

    // these devServer options should be customized in /config/index.js
    devServer: {
      clientLogLevel: 'warning',
      historyApiFallback: {
        rewrites: [
          { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') }
        ]
      },
      hot: true,
      contentBase: false, // since we use CopyWebpackPlugin.
      compress: true,
      host: HOST || config.dev.host,
      port: PORT || config.dev.port,
      open: config.dev.autoOpenBrowser,
      overlay: config.dev.errorOverlay
        ? { warnings: false, errors: true }
        : false,
      publicPath: config.dev.assetsPublicPath,
      proxy: config.dev.proxyTable,
      disableHostCheck: true,
      inline: true,
      quiet: true, // necessary for FriendlyErrorsPlugin
      watchOptions: {
        poll: config.dev.poll
      }
    },
    plugins: [
      new webpack.DefinePlugin({
        'process.env': require('../config/dev.env')
      }),
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
      new webpack.NoEmitOnErrorsPlugin(),
      // https://github.com/ampedandwired/html-webpack-plugin
      new HtmlWebpackPlugin({
        filename: 'index.html',
        template: 'index.html',
        inject: true
      }),
      // copy custom static assets
      new CopyWebpackPlugin([
        {
          from: path.resolve(__dirname, '../static'),
          to: config.dev.assetsSubDirectory,
          ignore: ['.*']
        }
      ])
    ]
  }
})

module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = process.env.PORT || config.dev.port
  portfinder.getPort((err, port) => {
    if (err) {
      reject(err)
    } else {
      // publish the new Port, necessary for e2e tests
      process.env.PORT = port
      // add port to devServer config
      devWebpackConfig.devServer.port = port

      // Add FriendlyErrorsPlugin
      devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
        compilationSuccessInfo: {
          messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`]
        },
        onErrors: config.dev.notifyOnErrors
          ? utils.createNotifierCallback()
          : undefined
      }))

      resolve(devWebpackConfig)
    }
  })
})

// module.exports = devWebpackConfig

Due to heavy struggle I recently decided to cut out the ' new portfinder Promise 'and provide module.exports directly with devWebpackConfig. 由于艰苦奋斗,我最近决定删掉新的portfinder Promise ”,并直接使用devWebpackConfig提供module.exports。

If I comment out and include the just mentioned parts, I run into this: 如果我注释掉并包括刚才提到的部分,则会遇到以下问题:

    > ulsvr@1.0.0 dev C:\Users\Rober\dev@localhost\www\uls
> webpack-dev-server --inline --progress --config build/webpack.dev.conf.js

× 「wds」: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.module has an unknown property 'plugins'. These properties are valid:
   object { defaultRules?, exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, strictExportPresence?, strictThisContextOnImports?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, wrappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp? }
   -> Options affecting the normal modules (`NormalModuleFactory`).
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! ulsvr@1.0.0 dev: `webpack-dev-server --inline --progress --config build/webpack.dev.conf.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ulsvr@1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Rober\AppData\Roaming\npm-cache\_logs\2019-03-03T07_26_58_948Z-debug.log

Finally maybe you could also need the important config requirement {root}/config/ index.js 最后,也许您还需要重要的配置要求{root} / config / index.js

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require('path')

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {},

    // Various Dev Server settings
    host: '0.0.0.0', // can be overwritten by process.env.HOST
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',

    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,

    cssSourceMap: true
  },

  build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',

    /**
     * Source Maps
     */

    productionSourceMap: true,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',

    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],

    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  }
}

Any help is appreciated! 任何帮助表示赞赏!

Original intention is to set up a vue dev environment on localhost:8080. 最初的意图是在localhost:8080上设置vue开发环境。 If I run ' vue ui 'in {root} I get: 如果我在{root}中运行' vue ui ',我得到:

  C:\\Users\\Rober\\dev@localhost\\www\\uls\u0026gt;vue ui 🚀 Starting GUI... 🌠 Ready on http://localhost:8000 

Am I doing something wrong when trying to run npm dev server with the script commands? 尝试使用脚本命令运行npm dev服务器时,我做错什么了吗? My goal is also to set up a node proxy back to my golang echo server (listening on :80) when request header says something like '/do'. 我的目标也是在请求标头显示类似'/ do'的情况下,将节点代理设置回我的golang回显服务器(侦听:80)。 Proxy already works fine with the solution provided by valued Stackoverflower Yevgen Safronov in webpack-dev-server proxy dosen't work 代理已经可以在webpack-dev-server代理中由尊贵的Stackoverflower Yevgen Safronov提供的解决方案很好地工作

But webpack-dev-server does not. 但是webpack-dev-server没有。 It did before, but then (almost out of nowhere) it prompts me to fix this first. 它以前做过,但是随后(几乎无处不在)它提示我首先解决此问题。 Maybe I just have to recreate my whole project. 也许我只需要重新创建我的整个项目。

Try copy your devServer upper like this 尝试像这样复制您的devServer上层

const devWebpackConfig = merge(baseWebpackConfig, {
    devServer: {
        clientLogLevel: 'warning',
        historyApiFallback: {
            rewrites: [
                { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') }
            ]
        },
        hot: true,
        contentBase: false, // since we use CopyWebpackPlugin.
        compress: true,
        host: HOST || config.dev.host,
        port: PORT || config.dev.port,
        open: config.dev.autoOpenBrowser,
        overlay: config.dev.errorOverlay ?
            { warnings: false, errors: true } :
            false,
        publicPath: config.dev.assetsPublicPath,
        proxy: config.dev.proxyTable,
        disableHostCheck: true,
        inline: true,
        quiet: true, // necessary for FriendlyErrorsPlugin
        watchOptions: {
            poll: config.dev.poll
        }
    },
    module: {
        rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }),
        // cheap-module-eval-source-map is faster for development
        devtool: config.dev.devtool,

        // these devServer options should be customized in /config/index.js
        devServer: {
            clientLogLevel: 'warning',
            historyApiFallback: {
                rewrites: [
                    { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') }
                ]
            },
            hot: true,
            contentBase: false, // since we use CopyWebpackPlugin.
            compress: true,
            host: HOST || config.dev.host,
            port: PORT || config.dev.port,
            open: config.dev.autoOpenBrowser,
            overlay: config.dev.errorOverlay ?
                { warnings: false, errors: true } :
                false,
            publicPath: config.dev.assetsPublicPath,
            proxy: config.dev.proxyTable,
            disableHostCheck: true,
            inline: true,
            quiet: true, // necessary for FriendlyErrorsPlugin
            watchOptions: {
                poll: config.dev.poll
            }
        },
        plugins: [
            new webpack.DefinePlugin({
                'process.env': require('../config/dev.env')
            }),
            new webpack.HotModuleReplacementPlugin(),
            new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
            new webpack.NoEmitOnErrorsPlugin(),
            // https://github.com/ampedandwired/html-webpack-plugin
            new HtmlWebpackPlugin({
                filename: 'index.html',
                template: 'index.html',
                inject: true
            }),
            // copy custom static assets
            new CopyWebpackPlugin([{
                from: path.resolve(__dirname, '../static'),
                to: config.dev.assetsSubDirectory,
                ignore: ['.*']
            }])
        ]
    }
})

After playing around for too many hours I finally managed to get it back to work again. 在玩了很多小时之后,我终于设法重新恢复了工作。 Still can't use npm run dev (throwing same port error) but instead I came across this article: exploring zero config with vue 仍然不能使用npm run dev (抛出相同的端口错误),但是我碰到了这篇文章:用vue探索零配置

And from now on I'll start my dev server successfully with the vue-cli-service serve --open command. 从现在开始,我将使用vue-cli-service serve --open命令成功启动我的开发服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM