首页 文章

如何配置Webpack dev服务器以在通过其他服务器运行其余站点时为特定文件夹提供服务?

提问于
浏览
3

一些快速背景:

我公司的网站运行CMS,CMS处理所有路由 . 没有html文件,只有剃刀文件(.cshtml) . 虽然从头开始重做网站是我更喜欢做的,但它不是一个选项,所以我试图通过逐页整合vue.js与webpack开发工作流程来逐步实现网站的现代化 . 基础 .

我花了很多时间设置webpack,只允许它处理在/ dist /文件夹中找到的文件 - 其他一切都通过http://my.server/提供,并由CMS和后端处理 .

通过反复试验,我设法在/ dist /文件夹中获取webpack-dev-server服务文件,同时允许服务器的其余部分提供其他所有服务(通过http://my.server/) . 不幸的是,只有当webpack-dev-server部分的文件路径具体引用“http://localhost:8080/”时,这才有效,这显然是不可接受的 .

开发环境代码必须与 生产环境 环境代码完全相同,因此 <script src="http://localhost:8080/dist/build.js"></script> 是不可接受的 .

但是,如果我只是写 <script src="/dist/build.js"></script> ,服务器将其解析为 <script src="http://my.server/dist/build.js"></script> ,这显然是不正确的,并导致404(因为这些文件仅从开发服务器提供) .

我的问题是,"how do I configure the webpack-dev-server to serve everything in the /dist/ folder from itself, while allowing everything else on the site to be served via " http://my.server“?

这是我的webpack.config.js文件供参考:

var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
            // the "scss" and "sass" values for the lang attribute to the right configs here.
            // other preprocessors should work out of the box, no loader config like this nessessary.
            'scss': 'vue-style-loader!css-loader!sass-loader',
            'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.common.js'
    }
  },
  devServer: {
    publicPath: '/dist/',
    historyApiFallback: true,
    noInfo: false,
    proxy: [{
      context: function(pathname, req) {
        // exclude /src/ and /dist/
        return !pathname.match("^/(src|dist)/");
      },
      target: {
        "host": "my.server",
        "protocol": 'http:',
        "port": 80
      },
      ignorePath: false,
      changeOrigin: true,
      secure: false
    }]
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

虽然可能没有必要回答这个问题,但如果您想要其他背景知识,我的初始问题(以及该问题的解决方案)就在这里:Using a simple vue.js/webpack setup, how does one configure the dev server to proxy everything EXCEPT a few .js and .vue files?

3 回答

  • 0

    更改webpack配置的publicPath:'/ dist /'以匹配您的实际产品路径,然后将index.html中的脚本SRC更改为指向新的公共路径..即基本上虚拟路径...不一定需要存在在实际的文件系统..我已经在我的项目中实现了相同的..

  • 0

    认为问题是由使用此主机引起的: http://my.server 而不是默认 http://localhost:8080

    尝试使用标志 --host 0.0.0.0--port 80 启动webpack-dev-server

    `--host <hostname/ip>`: hostname or IP. `0.0.0.0` binds to all hosts.
    

    https://webpack.github.io/docs/webpack-dev-server.html#webpack-dev-server-cli

  • 0

    我主要使用.NET应用程序 . 它仍然提供来自 localhost:8080 的开发文件,但负责在开发期间为您修改模板文件并将其调整回 生产环境 . 不确定它是否会完全解决你的问题,但是无论如何它都会留在这里 .

    package.json 我有一个开始(dev)和构建(prod)脚本:

    "start": "webpack --config webpack.dev.js && webpack-dev-server --config webpack.dev.js",
    "build": "webpack --config webpack.prod.js"
    

    webpack.prod.js 只需设置 mode: "production" 并与 webpack.config.js 合并,后者执行大部分webpack工作,包括将文件注入.net _Layout_React.cshtml 文件,包括 Scripts 文件夹中的制作脚本:

    const HtmlWebPackPlugin = require('html-webpack-plugin');
    const webpack = require('webpack');
    const path = require('path');
    
    module.exports = {
      entry: {
        main: './src/index.js',
      },
      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
              loader: 'babel-loader',
            },
          },
          {
            test: /\.html$/,
            use: [
              {
                loader: 'html-loader',
              },
            ],
          },
          {
            test: /\.scss$/,
            use: [
              'style-loader', // creates style nodes from JS strings
              'css-loader', // translates CSS into CommonJS
              'sass-loader', // compiles Sass to CSS, using Node Sass by default
            ],
          },
        ],
      },
      plugins: [
        new HtmlWebPackPlugin({
          template: '../../../Views/Shared/_Layout_Template.cshtml',
          filename: '../../Views/Shared/_Layout_React.cshtml',
        }),
        new webpack.HashedModuleIdsPlugin(),
      ],
      output: {
        path: path.resolve(__dirname, '../../../Scripts/React/'),
        publicPath: '/Scripts/React/',
        filename: '[name].[contenthash].production.js',
      },
      optimization: {
        runtimeChunk: 'single',
        splitChunks: {
          cacheGroups: {
            vendor: {
              test: /[\\/]node_modules[\\/]/,
              name: 'vendor',
              chunks: 'all',
            },
          },
        },
      },
    };
    

    当我运行 npm run build 时,这将构建 生产环境 _Layout_React.cshtml 模板,该模板在应用程序中使用,并包含来自文件系统的文件 . 但是,当我运行 npm start 时,它会更改 _Layout_React.cshtml 模板以包含 localhost:8080 中的文件,这是运行 webpack-dev-server 并从以下位置提供监视文件的位置:

    webpack.dev.js

    const merge = require('webpack-merge');
    const HtmlWebPackPlugin = require("html-webpack-plugin");
    const webpack = require('webpack');
    const baseConfig = require('./webpack.config.js');
    
    module.exports = merge(baseConfig, {
        mode: "development",
        devtool: 'eval-source-map',
        devServer: {
            open: false,
        },
        output: {
            filename: '[name].development.js',
            publicPath: 'http://localhost:8080/dist/',
        },
    });
    

    现在,当我运行 npm start 然后运行.NET应用程序时,我在 localhost:33401 上获得了.NET应用程序,但是's getting it'会对 localhost:8080 中的文件做出反应并在保存时自动编译它们,当它需要推送到repo时我运行 npm run build 并构建了将文件存入.NET Scripts 文件夹中的硬文件并更新模板以反映此情况 .

相关问题