要在 TS 中使用的 SCSS 导出的汇总生成失败 ( [!]错误:'default'不是由 src/styles/variables.scss 导出的)



我遇到了以下汇总构建失败,我希望能够在打字稿文件中使用来自 scss 文件的导出。

生成失败如下所示:

[!错误:"默认"未由 src/styles/variables.scss 导出, 导入者 src/components/Layout/Layout.themes.tsx https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module src/components/Layout/Layout.themes.tsx (1:7( 1:从 '../../styles/variables.scss';

我的汇总配置如下所示:

import scss from 'rollup-plugin-scss';
import typescript from 'rollup-plugin-typescript2';
import image from '@rollup/plugin-image';
import { terser } from 'rollup-plugin-terser';
import pkg from './package.json';
export default {
input: ['src/index.tsx'],
output: [
{
file: pkg.main,
format: 'cjs',
sourcemap: true,
name: 'Main'
},
{
file: pkg.module,
format: 'esm',
sourcemap: true,
name: 'tree-shaking'
}
],
external: [...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.devDependencies || {}), ...Object.keys(pkg.peerDependencies || {})],
plugins: [image(), scss({ output: 'dist/styles.css' }), typescript({ useTsconfigDeclarationDir: true }), terser()]
};

变量.scss包含:

// colors
$color-blue: #1c4077;
$color-orange: #e87d1e;
:export {
colorBlue: $color-blue;
colorOrange: $color-orange;
}

变量.scss.d.ts 类型文件包含:

export interface IGlobalScss {
colorBlue: string;
colorOrange: string;
}
export const variables: IGlobalScss;
export default variables;

Layout.themes.tsx文件如下:

import vbl from '../../styles/variables.scss';
export const myTheme = {
headerColor: vbl.colorBlue,
footerColor: vbl.colorOrange
}

我尝试导入非默认导出import { variables } from '../../styles/variables.scss';但它也失败了:

[!错误:"变量"未由 src/styles/variables.scss 导出, 导入者 src/components/Layout/Layout.themes.tsx https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module src/components/Layout/Layout.themes.tsx (1:9( 1:import { 变量 } 来自 '../../styles/variables.scss';

我能够通过故事书为项目提供服务,但是当我通过汇总构建时,我遇到了上面列出的错误。请协助我解决此构建失败?

下面是此示例的 CodeSandbox。提取拉链、纱线并运行纱线开始纱线构建以在 VSCode 中进行测试。您会注意到纱线启动成功,而纱线构建将失败,如上所述。

我认为问题是output属性不是的。

以下是当该属性设置为 false 时插件执行的操作:

if (options.output === false) {
const css = compileToCSS(code)
return {
code: 'export default ' + JSON.stringify(css),
map: { mappings: '' }
}
}

这发生在transform hook中,它在解析发生之前被调用。这很重要,因为export default ...被视为一个模块,这意味着您可以将其导入 js 文件中。

所以我认为您必须手动将该variables文件捆绑在一起:

scss({ output: false }).

现在,出现了另一个问题:当您从.scss文件导入时,您将获得字符串化的:export对象。

例如:

"export default ":export {n  colorBlue: #1c4077;n  colorOrange: #e87d1e; }n""

正在使用的插件似乎无法处理这种情况。

所以我认为解决方案涉及操作该字符串,以便您最终得到这样的东西:

`{ colorX: 'value', colorY: 'value' }`

相关内容

最新更新