diff --git a/.fatherrc.ts b/.fatherrc.ts index 33c05fd0..2ecb09a0 100644 --- a/.fatherrc.ts +++ b/.fatherrc.ts @@ -1,8 +1,29 @@ import { defineConfig } from 'father'; +import { IFatherBundlessConfig } from 'father/dist/types'; + +const less2CssConfig: IFatherBundlessConfig = { + transformer: 'babel', // 使用 babel 编译 + extraBabelPlugins: [ + [ + './scripts/babel-less-to-css.js', // 把文件中的 '.less' 字符转为 '.css' + { test: '\\.less' }, + ], + ], +}; export default defineConfig({ - esm: { output: 'es' }, - cjs: { output: 'lib' }, + esm: { + output: 'es', + ...less2CssConfig, + }, + cjs: { + output: 'lib', + ...less2CssConfig, + }, + plugins: [ + // less 编译为 css + './scripts/father-plugin-less.js', + ], // https://github.com/umijs/father/blob/master/docs/config.md#umd umd: { name: 'LarkMap', diff --git a/scripts/babel-less-to-css.js b/scripts/babel-less-to-css.js new file mode 100644 index 00000000..9c993052 --- /dev/null +++ b/scripts/babel-less-to-css.js @@ -0,0 +1,17 @@ +// https://github.com/umijs/father/blob/father-build%401.22.5/packages/father-build/src/getBabelConfig.ts#L25 + +const transformImportLess2Css = () => { + return { + name: 'transform-import-less-to-css', + visitor: { + ImportDeclaration(path) { + const re = /\.less$/; + if (re.test(path.node.source.value)) { + path.node.source.value = path.node.source.value.replace(re, '.css'); + } + }, + }, + }; +}; + +module.exports = transformImportLess2Css; diff --git a/scripts/father-plugin-less.js b/scripts/father-plugin-less.js new file mode 100644 index 00000000..9729358b --- /dev/null +++ b/scripts/father-plugin-less.js @@ -0,0 +1,17 @@ +// https://github.com/hexh250786313/blog/issues/30 +const { addLoader } = require('father/dist/builder/bundless'); + +module.exports = async (api) => { + const loaders = await api.applyPlugins({ + key: 'addPostcssLoader', + initialValue: [ + { + key: 'less-to-css', + test: /\.less$/, + loader: require.resolve('./loader-less-to-css'), // less 文件转 css 文件 + }, + ], + }); + + loaders.forEach((loader) => addLoader(loader)); +}; diff --git a/scripts/loader-less-to-css.js b/scripts/loader-less-to-css.js new file mode 100644 index 00000000..68396b94 --- /dev/null +++ b/scripts/loader-less-to-css.js @@ -0,0 +1,29 @@ +const path = require('path'); +const less = require('less'); +const postcss = require('postcss'); +const syntax = require('postcss-less'); +const autoprefixer = require('autoprefixer'); + +const loader = function (lessContent) { + const cb = this.async(); + this.setOutputOptions({ + ext: '.css', + }); + postcss([autoprefixer({})]) + .process(lessContent, { syntax }) + .then((result) => { + // less 转 css + less.render(result.content, (err, css) => { + if (err) { + console.error(err); + return; + } + cb(null, css.css); + }); + }) + .catch((err) => { + console.error(err); + }); +}; + +module.exports = loader;