umijs / father

NPM package development tool
MIT License
2.12k stars 273 forks source link

bundless 模式下更改scss 或者less路径 #679

Open wizard-a opened 1 year ago

wizard-a commented 1 year ago

father4.0 打包模块用Bundless模式,只处理.js .ts 文件,但有些scss,或者less 文件在做引入的时候通过


@import '@/style/mixins.scss';

这种方式引入文件,编译后要把@换成相对路径,这块要怎么支持呢

PeachScript commented 1 year ago

暂不支持,非 js 文件目前均直接输出不做处理,只能先用相对路径

Col0ring commented 1 year ago

可以自己写一个 plugin 处理: plugin.ts

import type { IApi } from 'father';
import { addLoader, ILoaderItem } from 'father/dist/builder/bundless/loaders';

export default async (api: IApi) => {
  const loaders: ILoaderItem[] = await api.applyPlugins({
    key: 'addPostcssLoader',
    initialValue: [
      {
        key: 'father-postcss-loader',
        test: /\.(le|c)ss$/,
        loader: require.resolve('./loader'),
      },
    ],
  });

  loaders.forEach((loader) => addLoader(loader));
};

loader.js

const postcss = require('postcss');
const syntax = require('postcss-less');
const atImport = require('postcss-import');
const autoprefixer = require('autoprefixer');

const loader = function (content) {
  const cb = this.async();
  postcss([
    autoprefixer({
      overrideBrowserslist: ['last 10 versions'],
    }),
    atImport({
      resolve: (id) => {
        if (id.startsWith('@')) {
              console.log(this.resource)
              // your code
        }
        return id
      },
    }),
  ])
    .process(content, { syntax })
    .then((result) => {
      cb(null, result.content);
    })
    .catch(cb);
};

module.exports = loader;