Сборка производственного веб-пакета не находит файл CSS

У меня есть проект React и Redux, использующий Webpack для сборки, и я пытаюсь собрать для производства впервые. Я построил скелет этого проекта для своего проекта. В моем index.ejs файл (шаблон, который использует webpack для сборки), у меня есть эта строка:

<link rel="stylesheet" type="text/css" href="/vendor/ui-toolkit/css/nm/main.min.css" media="all">

После запуска npm run build и работает в результате index.html вывод, я получаю эту ошибку в консоли:

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3000/vendor/ui-toolkit/css/nm/main.min.css

Как мне включить эту таблицу стилей (и шрифты, которые находятся в той же папке) в сборку? Вот код:

В package.jsonВы можете видеть, что есть npm run build скрипт, который я запускаю для создания своей продукции dist папка.

package.json:

{
  "engines": {
    "npm": ">=3"
  },
  "scripts": {
    "open:src": "babel-node tools/srcServer.js",
    "open:dist": "babel-node tools/distServer.js",
    "clean-dist": "npm run remove-dist && mkdir dist",
    "remove-dist": "rimraf ./dist",
    "prebuild": "npm run clean-dist",
    "build": "babel-node tools/build.js && npm run open:dist"
  },
  "dependencies": {
    "babel-eslint": "7.0.0",
    "object-assign": "4.1.0",
    "react": "15.2.0",
    "react-dom": "15.2.0",
    "react-redux": "4.4.5",
    "react-router": "2.8.1",
    "react-router-redux": "4.0.6",
    "redux": "3.5.2",
    "redux-thunk": "2.1.0",
    "babel-polyfill": "6.13.0"
  },
  "devDependencies": {
    "babel-cli": "6.10.1",
    "babel-core": "6.10.4",
    "babel-loader": "6.2.4",
    "babel-plugin-react-display-name": "2.0.0",
    "babel-preset-es2015": "6.9.0",
    "babel-preset-react": "6.11.1",
    "babel-preset-react-hmre": "1.1.1",
    "babel-preset-stage-1": "6.5.0",
    "babel-register": "6.9.0",
    "browser-sync": "2.13.0",
    "chalk": "1.1.3",
    "coveralls": "2.11.11",
    "cross-env": "1.0.8",
    "css-loader": "0.23.1",
    "extract-text-webpack-plugin": "1.0.1",
    "file-loader": "0.9.0",
    "html-webpack-plugin": "2.22.0",
    "less": "2.7.1",
    "less-loader": "2.2.3",
    "node-sass": "3.8.0",
    "npm-run-all": "2.3.0",
    "open": "0.0.5",
    "prompt": "1.0.0",
    "replace": "0.3.0",
    "rimraf": "2.5.3",
    "sass-loader": "4.0.0",
    "style-loader": "0.13.1",
    "url-loader": "0.5.7",
    "webpack": "1.13.1",
    "webpack-dev-middleware": "1.6.1",
    "webpack-hot-middleware": "2.12.1",
    "webpack-md5-hash": "0.0.5"
  }
}

"build": скрипт npm работает babel-node tools/build.js, который выглядит так:

build.js:

import webpack from 'webpack';
import config from '../webpack.config.prod';
import {chalkError, chalkSuccess, chalkWarning, chalkProcessing} from './chalkConfig';
process.env.NODE_ENV = 'production'; // this assures React is built in prod mode and that the Babel dev config doesn't apply.

webpack(config).run((error, stats) => {
  if (error) { // so a fatal error occurred. Stop here.
    console.log(chalkError(error));
    return 1;
  }

  const jsonStats = stats.toJson();
  if (jsonStats.hasErrors) {
    return jsonStats.errors.map(error => console.log(chalkError(error)));
  }
  if (jsonStats.hasWarnings) {
    console.log(chalkWarning('Webpack generated the following warnings: '));
    jsonStats.warnings.map(warning => console.log(chalkWarning(warning)));
  }
  // if we got this far, the build succeeded.
  console.log(chalkSuccess('Your app is compiled in production mode in /dist. It\'s ready to roll!'));
  return 0;
});

Далее вы можете увидеть этот веб-пакет config is being imported from../webpack.config.prod` - вот этот файл:

webpack.config.prod.js:

import webpack from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import WebpackMd5Hash from 'webpack-md5-hash';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import autoprefixer from 'autoprefixer';
import path from 'path';

const GLOBALS = {
  'process.env.NODE_ENV': JSON.stringify('production'),
  __DEV__: false
};

export default {
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  debug: true,
  devtool: 'source-map', // more info:https://webpack.github.io/docs/build-performance.html#sourcemaps and https://webpack.github.io/docs/configuration.html#devtool
  noInfo: true, // set to false to see a list of every file being bundled.
  entry: path.resolve(__dirname, 'src/index'),
  target: 'web', // necessary per https://webpack.github.io/docs/testing.html#compile-and-test
  output: {
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/',
    filename: '[name].[chunkhash].js'
  },
  plugins: [
    // Hash the files using MD5 so that their names change when the content changes.
    new WebpackMd5Hash(),

    // Optimize the order that items are bundled. This assures the hash is deterministic.
    new webpack.optimize.OccurenceOrderPlugin(),

    // Tells React to build in prod mode. https://facebook.github.io/react/downloads.html
    new webpack.DefinePlugin(GLOBALS),

    // Generate an external css file with a hash in the filename
    new ExtractTextPlugin('[name].[contenthash].css'),

    // Generate HTML file that contains references to generated bundles. See here for how this works: https://github.com/ampedandwired/html-webpack-plugin#basic-usage
    new HtmlWebpackPlugin({
      template: 'src/index.ejs',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true
      },
      inject: true,
      // Note that you can add custom options here if you need to handle other custom logic in index.html
      // To track JavaScript errors via TrackJS, sign up for a free trial at TrackJS.com and enter your token below.
      trackJSToken: ''
    }),

    // Eliminate duplicate packages when generating bundle
    new webpack.optimize.DedupePlugin(),

    // Minify JS
    new webpack.optimize.UglifyJsPlugin()
  ],
  module: {
    loaders: [
      {test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel'},
      {test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'url?name=[name].[ext]'},
      {test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url?limit=10000&mimetype=application/font-woff&name=[name].[ext]"},
      {test: /\.ttf(\?v=\d+.\d+.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream&name=[name].[ext]'},
      {test: /\.svg(\?v=\d+.\d+.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml&name=[name].[ext]'},
      {test: /\.(jpe?g|png|gif)$/i, loader: 'file?name=[name].[ext]'},
      {test: /\.ico$/, loader: 'file?name=[name].[ext]'},
      {test: /(\.css|\.scss)$/, loader: ExtractTextPlugin.extract('css?sourceMap!postcss!sass?sourceMap')}
    ]
  },
  postcss: ()=> [autoprefixer]
};

Есть идеи, почему он не может найти мою таблицу стилей? Как включить его в сборку веб-пакета и создать ссылку на него?

1 ответ

Вам не нужно изменять файл index.ejs. Оставьте это по умолчанию. Тогда в вашей главной index.js файл, просто импортируйте css, Webpack скомпилирует это.

Другие вопросы по тегам