webpack 如何打包多个主题文件

  1. react项目, 用的sass
  2. 三个主题编译文件 red.sass, blue.sass, yellow.sass
  3. 通过sass-resources-loader 注入主题变量
    在提取css的时候, 如果提取出三个主题的css?
    我看了 https://zhuanlan.zhihu.com/p/... 这个文章 能满足要求,但是extract-text-webpack-plugin 有不能用了呀。MiniCssExtractPlugin好像又不行。改如何解决呢
阅读 3.1k
1 个回答

我想你生成样式文件是为了动态换肤吧,那其实可以把这个流程从主构建流程中脱离出来,单独构建主题文件就行,可以参考下这个

import { renderSync } from 'sass'
import * as path from 'path'
import * as fs from 'fs'

// allow to import from node_modules
const tildeImporter = (url: string) => {
  if (url.includes('~')) {
    url = url.replace('~', '')

    if (!url.includes('.scss')) {
      url += '.scss'
    }

    url = require.resolve(url)
  }
  return { file: url }
}

async function compileSass(filePath: string) {
  const { css } = renderSync({
    file: filePath,
    importer: tildeImporter,
    outputStyle: 'compressed',
  })
  return css
}
const EXT_REGEXP = /\.\w+$/

function replaceExt(path: string, ext: string) {
  return path.replace(EXT_REGEXP, ext)
}

const THEME_DIR = path.join(__dirname, './themes')
const DIST_DIR = path.join(__dirname, './dist')

const buildThemes = async (dir: string) => {
  const themes: string[] = fs.readdirSync(dir)

  for (let i = 0; i < themes.length; ++i) {
    const filePath = path.join(dir, themes[i])
    const css = await compileSass(filePath)
    const outputPath = replaceExt(path.join(DIST_DIR, themes[i]), '.css')
    fs.writeFileSync(outputPath, css)
  }
}

buildThemes(THEME_DIR)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题