Webpack服务器配置+外部库

时间:2016-08-29 12:10:28

标签: reactjs webpack webpack-dev-server

我有以下webpack配置文件:

const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const LiveReloadPlugin = require('webpack-livereload-plugin');
const path = require('path');

module.exports = {
  entry: [
    'webpack-dev-server/client?http://0.0.0.0:2000', // WebpackDevServer host and port
    'webpack/hot/only-dev-server', // "only" prevents reload on syntax errors
    './app/index.tsx'
  ],
  output: {
    path: __dirname + '/dist/',
    filename: 'bundle.js'
  },

  devtool: 'source-map',

  resolve: {
    extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js']
  },

  module: {
    loaders: [
      {
        test: /\.tsx?$/,
        loaders: ['react-hot', 'ts'],
        include: path.join(__dirname, 'app')
      }
    ],

    preLoaders: [
      'source-map-loader'.
      {test: /\.js$/, loader: 'source-map-loader'}
    ]
  },

  plugins: [
    new CopyWebpackPlugin([
      {from: './app/index.html', to: './dist/index.html'}
    ]),
    new webpack.HotModuleReplacementPlugin()
  ],
  builds.
  externals: {
    'react': 'React',
    'react-dom': 'ReactDOM'
  }
};

这是我的服务器配置:

const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const config = require('./webpack.config');

new WebpackDevServer(webpack(config), {
  contentBase: './dist',
  publicPath: config.output.publicPath,
  hot: true,
  historyApiFallback: true,
  open: 'http://localhost:2000'
}).listen(2000, 'localhost', function (err, result) {
  if (err) {
    return console.log(err);
  }

  console.log('Listening at http://localhost:2000/');
});

我希望能够从根路径访问该应用程序:http://localhost:2000而不是http://localhost:2000/dist

还有一件事,是否有办法将所有外部依赖项从node_modules移动到dist并使用webpack(不需要在script文件中包含index.html标记)?

2 个答案:

答案 0 :(得分:1)

在您的服务器配置上将public path更改为

publicPath: '/',

答案 1 :(得分:1)

首先,对于设置应用程序起点,您需要将publicPath设置为"/"publicPath: 'http://localhost:2000' 你的第二个问题

有没有办法通过webpack将所有外部依赖项从node_modules移动到dist?

您可以仅为外部模块使用不同的文件并捆绑该文件。你不需要处理index.html文件让webpack插件HtmlWebpackPlugin处理它。

第一步设置应用的入口点

entry: {
        'vendors': './src/vendors.ts',//your external libraries 
        'app': './src/main.ts' //your app
}

并且输出

output: {
    publicPath: '/',
    filename: '[name].js'//this will generate two different files app.js, vendor.js
}

如何添加HtmlWebpackPlugin

在插件中添加

new HtmlWebpackPlugin({
     template: "./src/index.html",
     minify:false
})

现在它将为您放置脚本标签