簡體   English   中英

webpack-dev-server npm運行dev引發TypeError:無法設置未定義的屬性“端口”

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

我正在本地win10 x64遠程主機上使用webpack,http-proxy-middleware(包括)運行節點v10.15.1,vue js,vue-cli和vue-loader。 另外,我成功安裝並導入了bootstrap v4和bootstrap-vue。

當我現在運行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

這是我的package.json ,可以在我的項目{root} =>中找到

{
  "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"
  }
}

我猜這個問題與某些軟件包由於版本不匹配而無法正確交互有關。 雖然這也可能是一個錯誤的配置。 我對所有這些都有點陌生,但我願意學習。

接下來是我的webpack配置

{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'
  }
}

而我的問題孩子{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

由於艱苦奮斗,我最近決定刪掉新的portfinder Promise ”,並直接使用devWebpackConfig提供module.exports。

如果我注釋掉並包括剛才提到的部分,則會遇到以下問題:

    > 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

最后,也許您還需要重要的配置要求{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
  }
}

任何幫助表示贊賞!

最初的意圖是在localhost:8080上設置vue開發環境。 如果我在{root}中運行' vue ui ',我得到:

嘗試使用腳本命令運行npm dev服務器時,我做錯什么了嗎? 我的目標也是在請求標頭顯示類似'/ do'的情況下,將節點代理設置回我的golang回顯服務器(偵聽:80)。 代理已經可以在webpack-dev-server代理中由尊貴的Stackoverflower Yevgen Safronov提供的解決方案很好地工作

但是webpack-dev-server沒有。 它以前做過,但是隨后(幾乎無處不在)它提示我首先解決此問題。 也許我只需要重新創建我的整個項目。

嘗試像這樣復制您的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: ['.*']
            }])
        ]
    }
})

在玩了很多小時之后,我終於設法重新恢復了工作。 仍然不能使用npm run dev (拋出相同的端口錯誤),但是我碰到了這篇文章:用vue探索零配置

從現在開始,我將使用vue-cli-service serve --open命令成功啟動我的開發服務器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM