首页 > 解决方案 > 在 webpack 中使用文件加载器导入更少的文件

问题描述

我想使用文件加载器生成版本化的较少文件导入

<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

在此处输入图像描述

标签: webpackwebpack-file-loader

解决方案


下面的配置可以按照您的意愿工作。你可以在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}`);

资产/样式.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 编译失败,出现 1 个错误
13:05:04

未找到此依赖项:

  • ./src/main.js 中的 @/assets/styles.less

要安装它,您可以运行: npm install --save @/assets/styles.less


推荐阅读