Webpack.config如何仅将index.html复制到dist文件夹

网络包 Webpack

GreenA

2020-03-20

我正在尝试自动化进入/ 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']
  }
}

我还想在运行webpack时将/ lib旁边目录中的main.html包含到/ dist文件夹中。我怎样才能做到这一点?

更新1 2017_____________

现在,我最喜欢的方法是将html-webpack-plugin模板文件与一起使用也要感谢大家接受的答案!这种方式的优点是索引文件也将开箱即用添加了cachbusted js链接!

第2518篇《Webpack.config如何仅将index.html复制到dist文件夹》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
古一小哥 2020.03.20

在Windows上可以正常使用:

  1. npm install --save-dev copyfiles
  2. package.json我有一个复制任务:"copy": "copyfiles -u 1 ./app/index.html ./deploy"

这将我的index.html从app文件夹移到deploy文件夹。

JinJinStafan 2020.03.20

我将在VitalyB的答案中添加一个选项:

选项3

通过npm。如果通过npm运行命令,则可以将此设置添加到package.json中(也可以在此处检出webpack.config.js)。对于开发运行npm start,在这种情况下,无需复制index.html,因为Web服务器将从源文件目录运行,并且bundle.js将在同一位置可用(bundle.js仅驻留在内存中,但是就像与index.html一起位于一样)。对于生产运行npm run build,一个dist文件夹将包含您的bundle.js和index.html使用很好的旧cp命令复制,如下所示:

"scripts": {
    "test": "NODE_ENV=test karma start",
    "start": "node node_modules/.bin/webpack-dev-server --content-base app",
    "build": "NODE_ENV=production node node_modules/.bin/webpack && cp app/index.html dist/index.html"
  }

更新:选项4

有一个copy-webpack-plugin,如本Stackoverflow答案中所述

但是通常,除了第一个文件(如index.html)和较大的资产(如大图像或视频)外,通过css,html,images等直接包含在您的应用中,require并且webpack会为您提供该文件(好吧,在使用加载程序和可能的插件正确设置好它之后)。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android