将我的包放在非根文件夹中

Having my bundle in a non-root folder

我正在用 react 使用 webpack 创建一个网站。

目前我的 webpack.config.js 看起来像这样:

var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: './scripts/main.js',
  output: {
    path: __dirname,
    filename: 'bundle.js'  
  },
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query:{
          presets: ['es2015', 'react']
        }
      }
    ]
  }
}

然后我使用 webpack-dev-server --progress --colors 启动开发服务器,每当我更改 javascript 文件时,我的网页都会刷新,一切似乎都运行良好。但是,我希望我的 bundle.js 文件位于根文件夹之外的另一个文件夹中。因此,我将行 path: __dirname, 更改为 path: __dirname + '/dist',.

现在,当我更改脚本文件时,捆绑包不会自动更新,但如果我手动 运行 webpack 命令,它就会构建。所以我的问题是:将我的 bundle.js 文件放入 dist 文件夹并在我对脚本进行更改时仍然让 webpack-dev-server 自动更新的正确方法是什么?

这样的配置适合我:

var path = require('path');

output: {
    path: path.join(__dirname, 'dist'),
    filename: "[name].js"
},

还要确保您的 webpack 配置放置在相对于此路径文件夹中。

P.S。还可以查看 browser-sync 而不是 dev-server 模块。因为它调用所有加载器等,并支持热模块等。

P.S.2。 来自 webpack 开发服务器 official page

It will not be written to your configured output directory

所以我建议您使用浏览器异步插件来获得相同的功能。

你可以找到一个例子here

您可以使用 output.publicPath 告诉 webpack 开发服务器从哪里提供您的捆绑文件。

The Webpack Dev Server also takes a hint from publicPath using it to determine where to serve the output files from.

webpack.config.js

output: {
  path: __dirname + '/dist',
  filename: 'bundle.js',
  publicPath: '/dist/'
},

如果您想 bundle.js 位于路由以外的其他位置,我发现您可以将整个路径放在文件名中。

output: {
  path: __dirname + '/public',
  filename: 'static/assets/script/app.bundle.js'
},