简体   繁体   English

如何使用 webpack 在静态 html 页面中导入静态资产?

[英]How do I import static assets in a static html page with webpack?

Problem Context问题背景

I have webpack working for compiling my typescript into javascript.我有 webpack 用于将我的打字稿编译成 javascript。 Automatic reloading works when I change my typescript code.当我更改打字稿代码时,自动重新加载工作。 However, webpack is not watching my static html file.但是,webpack 并没有监视我的静态 html 文件。

.
├── dist
│   ├── index.html
│   └── style.css
├── src
│   └── index.ts
└── webpack.config.js

The problem is I need to make several changes in my index.html and webpack does not automatically detect those changes.问题是我需要在index.html进行一些更改,而 webpack 不会自动检测到这些更改。 And, if I refresh the html page, it seems to break webpack's webpack-dev-server.而且,如果我刷新 html 页面,它似乎会破坏 webpack 的 webpack-dev-server。

Expected Output预期产出

I want everything to be in the src folder and when I run webpack I have a fully working static site in my dist folder.我希望所有内容都在src文件夹中,当我运行webpack时,我的dist文件夹中有一个完全webpack静态站点。 That is:那是:

.                                      .
├── dist                               ├── dist
├── src                                │   ├── index.html
│   ├── index.html                     │   ├── bundle.js
│   ├── index.ts      npx webpack ->   │   └── style.css
│   └── style.css                      ├── src
└── webpack.config.js                  │   ├── index.html
                                       │   ├── index.ts
                                       │   └── style.css 
                                       └── webpack.config.js 

The files in the dist folder might have hashed filenames. dist文件夹中的文件可能具有散列文件名。 I'm not worrying about that step for now though.不过,我现在并不担心这一步。 I expect that webpack will go through my files and make sure they link to the correct resources.我希望 webpack 会检查我的文件并确保它们链接到正确的资源。 So if webpack were to give style.css a hashed name, the href in index.html would be updated.因此,如果 webpack 给style.css一个散列名称, index.html的 href 将被更新。

Current Output电流输出

My current solution outputs both index.html and bundle.js , but I cannot get it to copy style.css into the dist folder.我当前的解决方案同时输出index.htmlbundle.js ,但我无法将style.css复制到dist文件夹中。 My current webpack.config.js looks like the this:我当前的webpack.config.js看起来像这样:

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

module.exports = {
  entry: './src/index.ts',
  devtool: 'inline-source-map',
  mode: 'development',
  devServer: {
      contentBase: './dist'
  },
  module: {
      rules: [
        {
            test: /\.tsx?$/,
            use: 'ts-loader',
            exclude: /node_modules/
        },
        {
            test: /\.css$/,
            use: [
                'style-loader',
                'css-loader'
            ]
        },
        {
            test: /\.html$/,
            use: [
                { loader: 'file-loader?name=[name].[ext]' },
                { loader: 'extract-loader' },
                { loader: 'html-loader' }
            ]
        }
      ]
  },
  plugins: [
    new CleanWebpackPlugin()
  ],
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

And my index.html looks like this:我的index.html看起来像这样:

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8"> 
    <title>stuff</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <script src="./bundle.js" charset="utf-8"></script>
  </body>
</html>

My index.ts contains:我的index.ts包含:

import './index.html';

What I Tried我试过的

At first I tried just adding an import for my css into my index.ts :起初,我尝试将我的 css 导入添加到我的index.ts

import './style.css';

But this did not work.但这不起作用。 Next I looked at the html-loader documentation, and it seemed to hint at what I'm looking for:接下来我查看了 html-loader 文档,它似乎暗示了我在寻找什么: https://webpack.js.org/loaders/html-loader/ However, I've read that inlining loaders like that is deprecated, and looking through the source there doesn't seem to be any configuration option for interpolation.但是,我已经读过类似这样的内联加载器已被弃用,并且查看源代码似乎没有任何用于插值的配置选项。 I tried to do it as described in the documentation anyways, but it either simply does not work, or gives me some error message about require not found (I can't seem to reproduce that error though).无论如何,我试图按照文档中的描述进行操作,但它要么根本不起作用,要么给了我一些关于require not found 的错误消息(虽然我似乎无法重现该错误)。 My index.html contained:我的index.html包含:

<link rel="stylesheet" href="${require(`style.css`)">

and index.ts contained:index.ts包含:

require("html-loader?interpolate=require!./index.html");

How do I get webpack to move my style.css to the dist folder?如何让 webpack 将我的style.css移动到 dist 文件夹?

I have the hunch I'm misunderstanding how webpack is supposed to be used.我有一种预感,我误解了应该如何使用 webpack。 When I have something working can I post my webpack config on the code review stack exchange to get help creating a more idiomatic webpack config?当我有一些工作时,我可以在代码审查堆栈交换中发布我的 webpack 配置以获得帮助来创建更惯用的 webpack 配置吗?

  1. When creating a CSS file, try using MiniCssExtractPlugin to write CSS to a new file import './style.css';创建 CSS 文件时,尝试使用 MiniCssExtractPlugin 将 CSS 写入新文件 import './style.css'; - this should work, but write CSS inline in the head of html. - 这应该可行,但在 html 的头部内联编写 CSS。

    { use: [MiniCssExtractPlugin.loader, 'css-loader'] } { 使用: [MiniCssExtractPlugin.loader, 'css-loader'] }

  2. For file name pattern: [name].[contenthash].bundle.js对于文件名模式:[name].[contenthash].bundle.js

  3. Use HtmlWebpackPlugin for auto updating [contenthash]使用 HtmlWebpackPlugin 自动更新 [contenthash]

     const plugins = () => { const result = [ new HtmlWebpackPlugin({ template: "./index.html", // this file will be used as html and all css/js will be automaticly included }) ]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM