webpack生产配置(react,es6)

时间:2016-08-01 12:10:55

标签: node.js reactjs webpack react-router webpack-dev-server

我使用ES6,react和react-router进行站点开发的webpack配置。它使用具有热重载和路由的开发人员服务器。

/config/webpack.dev:

var webpack = require('webpack');
var path = require('path');
var APP_DIR = path.join(__dirname, '..', 'app');

module.exports = {
  debug: true,
  devtool: 'eval',
  entry: ['webpack-hot-middleware/client', './app/index.js'],
  module: {
    preLoaders: [{
      test: /\.js?$/,
      loaders: ["babel-loader", "eslint-loader"],
      exclude: /node_modules/,
      include: APP_DIR
    }],
    loaders: [
      {test: /\.js?$/, loaders: ['react-hot', 'babel'], include: APP_DIR},
      {
        test: /\.scss$/, include: APP_DIR,
        loader: 'style!css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap'
      },
      {
        test: /\.css$/, include: APP_DIR,
        loader: "style!css!autoprefixer?browsers=last 2 version!"
      },
      {test: /\.(jpe?g|png|gif|svg)$/i, loaders: ['url?limit=8192', 'img']},
      {test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff"},
      {test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff"},
      {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream"},
      {test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file"}
    ]
  },
  output: {
    filename: 'app.js',
    path: path.join(__dirname, '..', 'build'),
    publicPath: '/static/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  resolve: {
    root: [path.resolve('../app')],
    extensions: ['', '.jsx', '.js']
  },
  sassLoader: {
    includePaths: [path.resolve(__dirname, "./app")]
  }
};

我通过 npm start 运行构建。我的 package.json 的片段:

...
scripts": {
    "build:webpack": "NODE_ENV=production webpack --config config/webpack.prod.js",
    "clean": "rimraf build",
    "start": "node dev_server.js"
}
...

dev_server.js:

var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./config/webpack.dev');

var app = express();
var compiler = webpack(config);
var port = process.env.PORT || 3000;

app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));
app.use(express.static(path.join(__dirname, '..', 'static')));

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.listen(port, 'localhost', err => {
  if (err) {
    console.log(err);
    return;
  }

  console.log(`Listening at http://localhost:${port}`);
});

我还有 /config/webpack.prod:

var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CleanPlugin = require('clean-webpack-plugin');

var APP_DIR = path.join(__dirname, '..', 'app');

var projectRootPath = path.resolve(__dirname, '../');
var assetsPath = path.resolve(projectRootPath, './build');

module.exports = {
  devtool: 'source-map',
  context: path.resolve(__dirname, '..'),
  entry: './app/index.js',
  module: {
    loaders: [
      {
        test: /\.js?$/,
        loaders: ['babel'],
        include: APP_DIR
      },
      {
        test: /\.scss$/, include: APP_DIR,
        loader: 'style!css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap'
      },
      {
        test: /\.css$/, include: APP_DIR,
        loader: "style!css!autoprefixer?browsers=last 2 version!"
      },
      {test: /\.(jpe?g|png|gif|svg)$/i, loaders: ['url?limit=8192', 'img']},
      {test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff"},
      {test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff"},
      {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream"},
      {test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file"},
      {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml"}]
  },
  output: {
    path: assetsPath,
    filename: 'app.js',
    publicPath: '/build/'
  },
  plugins: [
    new CleanPlugin([assetsPath], { root: projectRootPath }),
    new ExtractTextPlugin('[name]-[chunkhash].css', {allChunks: true}),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.DedupePlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false
      }
    })
  ],
  progress: true,
  resolve: {
    root: [path.resolve('../app')],
    extensions: ['', '.jsx', '.js']
  },
  sassLoader: {
    includePaths: [path.resolve(__dirname, "./app")]
  }
};

我通过 npm run build 运行它。它在app目录中生成文件。但是当我在浏览器中打开index.html时,页面是空的。在firefox检查员中我有评论: react-empty:1

如何使用webpack构建我的项目,以便在没有服务器的浏览器中使用它?

1 个答案:

答案 0 :(得分:0)

我建议使用write-file-webpack-plugin将捆绑的内容写入磁盘,您应该能够在浏览器中打开index.html并开始使用不带任何服务器的应用程序。

但请记住,如果您使用了来自'react-router'的browserHistory,那么在没有配置服务器的情况下它将无法工作。你必须用hashHistory替换它。

react-router documentation

  

哈希历史记录使用URL的哈希(#)部分创建路由   看起来像example.com /#/ some / path。

     

哈希历史记录无需配置您的服务器即可运行,所以如果您只是   入门,继续使用它。一般而言,生产   Web应用程序应该使用browserHistory来获得更干净的URL,以及   支持服务器端渲染,这是不可能的   hashHistory。