在使用Webpack构建dist文件夹后,如何将bundle.js和css文件移动到静态文件夹中?

8
当我运行npm run buildnpm run build-dev时。

enter image description here

它会在根目录下创建index.html、manage2.bundle.js和manage2.css文件。我需要将这些文件移动到静态目录中。
因此,下面生成的index.html实际上可以正常工作,路径也是正确的。
<!doctype html>
<html lang="en">
<head>
    <title>Manage2</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="The TickerTags backend manage app">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300|Source+Sans+Pro:200,600" rel="stylesheet">
    <link rel="icon" type="image/x-icon" href="static/favicon.ico">
<link href="/static/manage2.css" rel="stylesheet"></head>
<body>
    <div id="manage2"></div>
<script type="text/javascript" src="/static/manage2.bundle.js"></script></body>
</html>

这是如何实现的?下面是webpack.config。
const fs = require('fs');
const webpack = require('webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const dist = path.resolve(__dirname, "dist");
const src = path.resolve(__dirname, "src");
const environment = process.env.NODE_ENV;

const stream = fs.createWriteStream("src/services/environment.js");
stream.once('open', function(fd) {
  stream.write('const env = "'+environment+'"\n');
  stream.write('export default env');
  stream.end();
});

module.exports = {
  context: src,
  entry: [
    "./index.js"
  ],
  output: {
    path: dist,
    filename: "manage2.bundle.js",
    publicPath: '/static/',
  },
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: ["babel-loader"]
      },
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallbackLoader: "style-loader",
          loader: ["css-loader", "sass-loader"],
          publicPath: dist
        })
      }
    ]
  },
  devServer: {
    hot: false,
    quiet: true,
    publicPath: "",
    contentBase: path.join(__dirname, "dist"),
    compress: true,
    stats: "errors-only",
    open: true
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "index.html"
    }),
    new ExtractTextPlugin({
      filename: "manage2.css",
      disable: false,
      allChunks: true
    }),
    new CopyWebpackPlugin([{ from: "static", to: "static" }])
  ]
};
// new webpack.DefinePlugin({ env: JSON.stringify(environment) })

我的npm脚本

"scripts": {
    "dev": "NODE_ENV=development webpack-dev-server --history-api-fallback",
    "prod": "NODE_ENV=production webpack-dev-server -p",
    "build": "NODE_ENV=production webpack -p",
    "build-dev": "NODE_ENV=production webpack -d",
2个回答

19
该配置将*.js和*.css文件保存到静态文件夹中。
 output: {
 // the output bundle
 filename: '[name].[hash].js',
 // saves the files into the dist/static folder
 path: path.resolve(__dirname, 'dist/static'),
 // set static as src="static/main.js as relative path
 publicPath: 'static/'
 },

使用HtmlWebpackPlugin,您可以从模板生成一个html文件。通过在Webpack插件部分配置,index.html将保存到dist文件夹中,并带有正确的路径指向*.js和*.css文件。
plugins: [
   // is only working with npm run build
   new HtmlWebpackPlugin({
    title: '',
    // save index.html one director back from the output path
    filename: '../index.html',
    template: 'index.template.ejs',
    hash: false
   }),
  ],

index.template.ejs

<html>
<head>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
  <title>
    <%= htmlWebpackPlugin.options.title %>
  </title>
</head>
<body>
</body>
</html>

结果在
<html>
 <head>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
  <title> 
  </title>          
  <link href="static/main.css" rel="stylesheet">
 </head>    
  <body>    
   <script type="text/javascript" src="static/main.js"></script>
  </body>    
</html>

enter image description here


2

你的output.path是不正确的。它应该是path.resolve(__dirname, 'dist', 'static')

现在你的output.path指向dist/static,请将publicPath设置回/


当我这样做之后,当我运行 npm run dev 时,我的本地主机:8080 不再工作。当我执行 npm run build 时,dist 文件夹内也出现了 Cannot GET / 的错误。我在 static 文件夹中使用了静态资源。 - Leon Gaban
为什么devServer的publicPath: ""?文档说它应该始终以斜杠开头和结尾。https://webpack.js.org/configuration/dev-server/#devserver-publicpath- - Doodlebot
此外,您可能需要修改devserver的contentBase以包括静态文件夹。我相信dist文件夹被认为是工作目录,因此不需要包含它。contentBase: path.join(__dirname, "static") - Doodlebot

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接