Skip to content

Commit

Permalink
build: esm cmj 模式打包 less2css
Browse files Browse the repository at this point in the history
  • Loading branch information
lvisei committed Sep 14, 2024
1 parent e3d9aad commit a898cf5
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 2 deletions.
25 changes: 23 additions & 2 deletions .fatherrc.ts
Original file line number Diff line number Diff line change
@@ -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',
Expand Down
17 changes: 17 additions & 0 deletions scripts/babel-less-to-css.js
Original file line number Diff line number Diff line change
@@ -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;
17 changes: 17 additions & 0 deletions scripts/father-plugin-less.js
Original file line number Diff line number Diff line change
@@ -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));
};
29 changes: 29 additions & 0 deletions scripts/loader-less-to-css.js
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit a898cf5

Please sign in to comment.