Webpack4 как загрузить изображения и пользовательские javascript непосредственно из файла HTML? - PullRequest
0 голосов
/ 23 февраля 2020

Я хочу загрузить изображения непосредственно из HTML с помощью Webpack 4 и добавить пользовательские файлы Javascript в мой файл HTML, но оба файла, проверенные на консоли, показывают Not found 404.

Как правильно загрузить изображения и файлы Javascipt с Webpack 4?

Мой конфигурационный файл Webpack 4:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
  entry: {
    main: "./src/index.js"
  },
  output: {
    path: path.join(__dirname, "../build"),
    filename: "[name].bundle.js"
  },
  mode: "development",
  devServer: {
    contentBase: path.join(__dirname, "../build"),
    compress: true,
    port: 3000,
    overlay: true
  },
  devtool: "cheap-module-eval-source-map",
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader" // transpiling our JavaScript files using Babel and webpack
        }
      },
      {
        test: /\.(sa|sc|c)ss$/,
        use: [
          "style-loader", // creates style nodes from JS strings
          "css-loader", // translates CSS into CommonJS
          "postcss-loader", // Loader for webpack to process CSS with PostCSS
          "sass-loader" // compiles Sass to CSS, using Node Sass by default
        ]
      },
      {
        test: /\.(png|svg|jpe?g|gif)$/,
        use: [
          {
            loader: "file-loader", // This will resolves import/require() on a file into a url and emits the file into the output directory.
            options: {
              name: "[name].[ext]",
              outputPath: "assets",
            }
          },
        ]
      },
      {
        test: /\.html$/,
        use: {
          loader: "html-loader",
          options: {
            attrs: ["img:src", ":data-src"],
            minimize: true
          }
        }
      }
    ]
  },
  plugins: [
    // CleanWebpackPlugin will do some clean up/remove folder before build
    // In this case, this plugin will remove 'dist' and 'build' folder before re-build again
    new CleanWebpackPlugin(),
    // The plugin will generate an HTML5 file for you that includes all your webpack bundles in the body using script tags
    new HtmlWebpackPlugin({
      template: "./src/index.html",
      filename: "index.html"
    }),
  ]

Мой webpack.prod. js Файл:

const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const CompressionPlugin = require("compression-webpack-plugin");
const TerserJSPlugin = require("terser-webpack-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack- 
plugin");
const BrotliPlugin = require("brotli-webpack-plugin");
const PurgecssPlugin = require('purgecss-webpack-plugin');
const glob = require("glob");

module.exports = {
entry: {
main: "./src/index.js"
},
output: {
path: path.join(__dirname, "../build"),
filename: "[name].[chunkhash:8].bundle.js",
chunkFilename: "[name].[chunkhash:8].chunk.js"
},
mode: "production",
module: {
rules: [
  {
    test: /\.js$/,
    exclude: /node_modules/,
    use: {
      loader: "babel-loader" // transpiling our JavaScript files using 
Babel and webpack
    }
  },
  {
    test: /\.(sa|sc|c)ss$/,
    use: [
      MiniCssExtractPlugin.loader,
      "css-loader", // translates CSS into CommonJS
      "postcss-loader", // Loader for webpack to process CSS with 
PostCSS
      "sass-loader" // compiles Sass to CSS, using Node Sass by 
default
    ]
  },
  {
    test: /\.(png|svg|jpe?g|gif)$/,
    use: [
      {
         loader: "file-loader", // This will resolves import/require() 
 on a file into a url and emits the file into the output directory.
        options: {
          name: "[name].[ext]",
          outputPath: "assets/"
        }
      },
    ]
  },
  {
    test: /\.html$/,
    use: {
      loader: "html-loader",
      options: {
        attrs: ["img:src", ":data-src"],
        minimize: true
      }
    }
  }
]
},
optimization: {
minimizer: [new TerserJSPlugin(), new OptimizeCSSAssetsPlugin()],
splitChunks: {
  cacheGroups: {
    commons: {
      test: /[\\/]node_modules[\\/]/,
      name: "vendors",
      chunks: "all"
    }
  },
  chunks: "all"
},
runtimeChunk: {
  name: "runtime"
}
},
plugins: [
// CleanWebpackPlugin will do some clean up/remove folder before build
// In this case, this plugin will remove 'dist' and 'build' folder 
before re-build again
new CleanWebpackPlugin(),
// PurgecssPlugin will remove unused CSS
new PurgecssPlugin({
  paths: glob.sync(path.resolve(__dirname, '../src/**/*'), { nodir: 
true })
}),
// This plugin will extract all css to one file
new MiniCssExtractPlugin({
  filename: "[name].[chunkhash:8].bundle.css",
  chunkFilename: "[name].[chunkhash:8].chunk.css",
}),
// The plugin will generate an HTML5 file for you that includes all 
 your webpack bundles in the body using script tags
new HtmlWebpackPlugin({
  template: "./src/index.html",
  filename: "index.html"
}),

Мой проект nesting:

--Build
--src
----html
----js
----styles
----assets
------images

Я хочу, чтобы файлы загружались просто:

<img src="assets/images/myimage.jpg">
<srcipt src="js/custom.js"></script>

Любая помощь приветствуется.

По иронии судьбы это мой второй проект с Webpack 4 и на этот раз я не могу решить эту проблему, в первый раз проблем не было.

1 Ответ

0 голосов
/ 23 февраля 2020

Вот как img работает в Webpack:

<img src=require("./assets/images/myimage.jpg")>

, если вы используете «require» с загрузчиком файлов, вам нужно добавить default.

 <img src=require("./assets/images/myimage.jpg").default>

Для скрипта tag, sr c должен быть вашим выходным файлом bundle.js; потому что Webpack записывает весь код в bundle.js с помощью Babel. Поэтому, когда браузер запрашивает html, браузер будет иметь только один Javascript файл, который является пакетом для загрузки. В этом вся суть пакета, меньший bundle.js лучше для производительности.

// According to your Webpack config, it is main.bundle.js
<srcipt src="main.bundle.js"></script>

но для того, чтобы браузер мог использовать этот main.bundle.js, он должен быть общедоступным. Поэтому вам нужно express для определения папки publi c, когда браузер ищет main.bundle.js, ваше приложение будет искать папку publi c и, если этот файл существует, оно отправит его в браузер.

const express = require("express");
const server = express();

const staticMiddleware = express.static("build");
server.use(staticMiddleware);
...