我试图自动化资产进入/dist。我有以下config.js:

module.exports = {
  context: __dirname + "/lib",
  entry: {
    main: [
      "./baa.ts"
    ]
  },
  output: {
    path: __dirname + "/dist",
    filename: "foo.js"
  },
  devtool: "source-map",
  module: {
    loaders: [
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader'
      },
      { test: /\.css$/, loader: "style-loader!css-loader" }
    ]
  },
  resolve: {
    // you can now require('file') instead of require('file.js')
    extensions: ['', '.js', '.json']
  }
}

我还想包括main.html从目录,坐在旁边/lib,到/dist文件夹时运行webpack。我该怎么做呢?

更新1 2017_____________

现在我最喜欢的方法是使用带有模板文件的html-webpack-plugin。也感谢公认的答案!这种方法的优点是,索引文件也将有cachbusted js链接添加开箱即用!


当前回答

Webpack 5附带了资产模块,所以你不再需要任何复制插件或文件加载器

其他回答

你可以使用CopyWebpackPlugin。它是这样工作的:

module.exports = {
  plugins: [
    new CopyWebpackPlugin([{
      from: './*.html'
    }])
  ]
}

您可以直接将索引添加到条目配置中,并使用文件加载器来加载它

module.exports = {

  entry: [
    __dirname + "/index.html",
    .. other js files here
  ],

  module: {
    rules: [
      {
        test: /\.html/, 
        loader: 'file-loader?name=[name].[ext]', 
      },
      .. other loaders
    ]
  }

}

Webpack 5附带了资产模块,所以你不再需要任何复制插件或文件加载器

我还发现把我的index.html文件放在dist/目录下,并将<script src='main.js'></script>添加到index.html中,以包括我绑定的webpack文件,这很简单,也很通用。如果在webpack的conf文件中没有指定其他的话,Main.js似乎是我们的bundle的默认输出名称。我想这不是一个好的和长期的解决方案,但我希望它能帮助理解webpack是如何工作的。

选项1

在你的index.js文件(即webpack条目)中,通过文件加载器插件在index.html中添加一个require,例如:

require(“file-loader ? name = [name]。[请拨分机!’…- index . html);

一旦你用webpack构建了你的项目,index.html就会在输出文件夹中。

选项2

使用html-webpack-plugin来避免使用index.html。简单地让webpack为你生成文件。

在这种情况下,如果你想保留自己的index.html文件作为模板,你可以使用这样的配置:

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  // ...
  plugins: [
    new HtmlWebpackPlugin({
      template: 'src/index.html'
    })
  ]
}

更多信息请参见文档。