如何配置Webpack dev服务器以在通过其他服务器运行其余站点时为特定文件夹提供服务? [英] How do you configure a Webpack dev server to serve a specific folder while running the rest of the site through a different server?

查看:107
本文介绍了如何配置Webpack dev服务器以在通过其他服务器运行其余站点时为特定文件夹提供服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一些快速背景:

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

My company's site runs off a CMS with the CMS handling all routing. There are no html files, only razor files (.cshtml). While redoing the site from scratch is what I'd prefer to do, it's not an option, so I'm attempting to modernize the site slowly over time by integrating vue.js with a webpack development workflow piecemeal on a page-by-page basis.

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

I've spent considerable time setting up webpack in a manner that allows it to process files found in the /dist/ folder only - everything else is served via http://my.server/ and handled by the CMS and backend.

通过试用和试用错误我设法让/ dist /文件夹中的webpack-dev-server服务文件,同时允许服务器的其余部分提供其他所有服务(通过 HTTP://my.server/ )。不幸的是,只有当webpack-dev-server部分的文件路径专门引用 http:// localhost:8080 / 这显然是不可接受的。

Through trial & error I managed to get webpack-dev-server serving files in the /dist/ folder while allowing the rest of the server to serve everything else (via http://my.server/). Unfortunately, this ONLY works when the file paths for the webpack-dev-server part are specifically referencing "http://localhost:8080/" which is obviously unacceptable.

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

The dev environment code must be exactly like the production environment code, therefore <script src="http://localhost:8080/dist/build.js"></script> is simply unacceptable.

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

However, if I simply write <script src="/dist/build.js"></script> the server resolves this to <script src="http://my.server/dist/build.js"></script> which is obviously incorrect and results in a 404 (because those files are being served only from the dev server).

我的问题是,我如何配置webpack-dev-server来为/ dist /文件夹中的所有内容提供服务,同时允许所有内容通过 http://my.server

My question is, "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文件供参考:

Here's my webpack.config.js file for reference:

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
    })
  ])
}

虽然可能没有必要回答这个问题,但如果您想要更多背景知识,我的初始问题(以及该问题的解决方案)就在这里:使用简单的vue.js / webpack设置,如何配置开发服务器代理所有内容除了几个.js和.vue文件?

While likely unnecessary to answer this question, if you'd like additional background, my initial problem (and solution to that problem) are located here: Using a simple vue.js/webpack setup, how does one configure the dev server to proxy everything EXCEPT a few .js and .vue files?

推荐答案

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

I've mostly got this working with a .NET app. It still serves the dev files from localhost:8080 but takes care of modifying the template files for you during dev and adjusting them back for production. Not sure if it would solve your problem entirely, that way, but it's working for us, for now and may help others, so I'll leave it here anyway.

package.json 我有一个start(dev)和build(prod)脚本:

In package.json I've got a start (dev) and build (prod) script:

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

webpack.prod.js 只需设置模式:production并与合并webpack.config.js 执行大部分webpack工作,包括将文件注入.net _Layout_React.cshtml 文件,包括来自的生产脚本 Scripts 文件夹:

webpack.prod.js just sets mode: "production" and merges with webpack.config.js which does most of the webpack stuff, including injecting the files into the .net _Layout_React.cshtml file including the productions scripts from the Scripts folder:

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 正在运行并从以下位置提供监视文件的地方:

When I run npm run build this builds the production _Layout_React.cshtml template which is used in the app and includes files from the filesystem. However, when I run npm start it changes the _Layout_React.cshtml template to include files from localhost:8080 which is where the webpack-dev-server is running and serving watched files from:

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应用程序,但它从 localhost获取它的反应文件:8080 并在保存时自动编译它们,当需要推送到repo时,我运行 npm run build 并将文件构建到.NET中的硬文件中脚本文件夹并更新模板以反映这一点。

Now when I run npm start then run the .NET app, I get .NET app on localhost:33401 but it's getting it's react files from localhost:8080 and auto-compiling them on save and when it's time to push to the repo I run npm run build and it builds the files into hard files in the .NET Scripts folder and updates the template to reflect this.

这篇关于如何配置Webpack dev服务器以在通过其他服务器运行其余站点时为特定文件夹提供服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆