在 webpack 中使用文件加载器导入更少的文件

Import less file using file-loader in webpack

我想使用 file-loader 来生成版本化的 less 文件导入

<link rel="stylesheet/less" type="text/css" href="/static/styles.<VERSION/HASH>.less" />

我希望我可以

import '@/assets/styles.less'

main.js.

我只需要这个来进行版本控制(每次修改我的 styles.less 文件时自动重命名文件),我不想在编译时少编译,因为我正在使用 less.modifyVars运行。所以我正在使用

import '@/assets/less.min.js'

搜索 rel="stylesheet/less" 标签并编译它。 当我手动添加 index.html

<link rel="stylesheet/less" type="text/css" href="/static/styles.less" />

一切正常,但我需要版本控制以实现持续交付

我尝试的是将下一条规则添加到加载程序:

{
    test: /\.less$/,
    loader: 'file-loader',
},

但是在编译过程中我得到:

ERROR  Failed to compile with 1 errors                                                                           13:05:04

This dependency was not found:

* @/assets/styles.less in ./src/main.js

To install it, you can run: npm install --save @/assets/styles.less

下面的配置如您所愿。您可以在 github 上找到此示例。

src/main.js:

import a from "@/assets/styles.less"

console.log(`You don't need to import less file here at all, only in index.ejs but if you need the reference, there you have it: ${a}`);

assets/styles.less

  // Variables
@link-color:        #428bca; // sea blue
@link-color-hover:  darken(@link-color, 10%);

// Usage
a,
.link {
  color: @link-color;
}
a:hover {
  color: @link-color-hover;
}
.widget {
  color: #fa0;
  background: @link-color;
}

webpack.config.js:

const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require('path')
module.exports = {
  entry: ['./src/main.js'],
  plugins: [
    new HtmlWebpackPlugin({template: 'src/index.ejs'}),
  ],
  devtool: '#source-map',
  resolve: {
    extensions: ['.less', '.js'], // not require
    alias: {'@': path.resolve(__dirname, 'src')}
  },
  module: {
    rules: [
      {
        test: /\.less$/,
        loader: 'file-loader',
        options: {
          publicPath: '', // you can override this to put less output in different folder
          name: 'static/[name].[ext]?[sha512:hash:base64:6]' // I guess you want the filename to stay the same after it's modified
        }
      },
    ],
  },
};

src/index.ejs:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet/less" type="text/css" href="<%= require('@/assets/styles.less') %>" />
</head>
<body>
</body>
</html>

请注意,下面的异常告诉您找不到文件 @/assets/styles.less。请确保您指定了正确的路径,如果您使用别名而不是相对路径,那么您在 webpack.config.js.

中有正确的别名

ERROR Failed to compile with 1 errors
13:05:04

This dependency was not found:

  • @/assets/styles.less in ./src/main.js

To install it, you can run: npm install --save @/assets/styles.less