Веб-пакет обслуживает различные файлы из корневого URL-адреса publicPath и дочернего URL-адреса после обновления - PullRequest
0 голосов
/ 28 сентября 2018

Когда я запускаю webpack-dev-server и захожу на него в моем браузере, все хорошо.Если я перехожу к дочерним страницам с помощью кликов / ссылок, все хорошо.Но если я затем нажму «Обновить», чтобы приложение загрузило дочерний URL-адрес напрямую, оно, похоже, не выполнит мое угловое приложение и не загрузит страницу.Единственное, что отображается, - это жестко закодированные элементы HTML в моем файле index.html.

Я также заметил, что когда я загружаю страницу из корневого URL-адреса, она загружает файлы из памяти, но когда я загружаюДочерний URL, похоже, загружает файлы из каталога dist, который, я думаю, является частью проблемы.Я смог подтвердить это, изменив файл HTML в каталоге dist напрямую.Когда я это сделал, я увидел свои изменения только при загрузке дочернего URL, где страница не загружалась правильно.

const path = require('path');
const webpack = require('webpack');
const getDefaultLoaders = require('./loaders.webpack.js');
var HtmlWebpackPlugin = require('html-webpack-plugin');

/**
 * Env
 * Get npm lifecycle event to identify the environment
 */
var ENV = process.env.npm_lifecycle_event || [];
var isTest = (ENV.indexOf('test') > -1); // lifecycle event contains 'test'
var isBuild = (ENV.indexOf('build') > -1); // lifecycle event contains 'build'


/**############ SOURCEMAPS AND UGLIFICATION SETUP #############**/
var config = {
  sourcemaps: !isBuild, // sourcemaps default to false when building, default to true o/w
  uglify: isBuild // uglify default to true when building, default to false o/w
};
/** Overrite with environment config  **/
readConfigFromEnv('sourcemaps', process.env.SOURCEMAPS);
readConfigFromEnv('uglify', process.env.UGLIFY);

function readConfigFromEnv(configName, envValue) {
  if (envValue !== undefined) {
    config[configName] = !!envValue;
  }
}

function getSourcemapOption() {
    return 'source-map';
}

module.exports = function(options) {


  var htmlWebpackPluginObj = options.htmlWebpackPluginObj || {};
  htmlWebpackPluginObj = Object.assign({
    title: options.HTMLPageTitle || 'MyApp',
    template: path.resolve(options.baseDir + '/app/index.ejs'),
    publicPath: options.publicPath,
    sourcemapsEnabled: config.sourcemaps,
    uglifyEnabled: config.uglify,
    packageJSONDeps: JSON.stringify(require(path.resolve(options.baseDir + '/package.json')).dependencies),
    versionUIScaffolding: getVersionForDependency(options, 'ui-scaffolding'),
    versionWorkbenchComponents: getVersionForDependency(options, 'workbench-components'),
    googleAnalyticsTag: getGoogleAnalyticsID(),
    versionBootstrap: getVersionForDependency(options, 'bootstrap'),
  }, htmlWebpackPluginObj);
  console.log('################## config', config);
  const defaultLoaders = getDefaultLoaders(config);

  console.log('########################### What mode are we using?', isBuild ? 'production' : 'development');

  function getPlugins() {
    const plugins = [];
    if (isTest) {
      return plugins;
    }

    plugins.push(
      new HtmlWebpackPlugin(htmlWebpackPluginObj)
    );

    return plugins;
  }

  return {
    mode: isBuild ? 'production' : 'development', // "production" | "development" | "none"
    // Chosen mode tells webpack to use its built-in optimizations accordingly.
    // entry: './app/app.js', // string | object | array  // defaults to ./src
    optimization: {
      splitChunks: {
        chunks: 'all'
      }
    },
    context: options.baseDir + '/app', // string (absolute path!)
    // the home directory for webpack
    // the entry and module.rules.loader option
    //   is resolved relative to this directory
    entry: {
      app: ['./app.js'],
      styles: './app.less'
    },  // Here the application starts executing
    // and webpack starts bundling
    output: isTest ? {} : {
      devtoolLineToLine: true,
      // options related to how webpack emits results
      path: path.resolve(__dirname, 'dist'), // string
      // the target directory for all output files
      // must be an absolute path (use the Node.js path module)
      filename: '[name].bundle.js', // string    // the filename template for entry chunks
      // filename: '[name].bundle.js', // string    // the filename template for entry chunks
      // sourceMapFilename: '[name].bundle.map',
      publicPath: '/contract-performance/', // string   // the url to the output directory resolved relative to the HTML page
      // publicPath: '/contract-performance/',
      library: 'contract-performance', // string,
      // the name of the exported library
      libraryTarget: 'umd', // universal module definition    // the type of the exported library
      /* Advanced output configuration (click to show) */
    },
    devServer: {
      // contentBase: './dist', // When commented out "Cannot GET /contract-performance/contracts"
      hot: false,
      historyApiFallback: true,
      publicPath: '/contract-performance/',
      // public: 'localhost/contract-performance/', Causes all kinds of issues in the log

      // publicPath: '/contract-performance/',
      // contentBase: './dist'
      // contentBase: path.join(__dirname, 'dist'),
      // publicPath: '/contract-performance/',
    },
    devtool: 'source-map', // enum  // enhance debugging by adding meta info for the browser devtools
    // source-map most detailed at the expense of build speed.
    target: 'web', // enum  // the environment in which the bundle should run
    plugins: getPlugins(),
    module: {
      rules: []
      .concat(defaultLoaders)
    },
  };
}
...