我正在使用Angular构建NativeScript应用程序,并且尝试实现主题切换,但是无法使其与Webpack捆绑一起使用。
我的版本:
7.2.12
7.2.3
2.0.0
3.2.2
我遵循了在Angular项目中实现该功能的教程:here和here。但是这些是针对非webpack(没有--bundle标志)的版本。使用bundle标志(以及更改described here),该开关将不再起作用,并且每个开关都会引发错误:
JS: ~/assets/themes/dark.scss
JS: Error: Css styling failed: Error: undefined:1:26: missing '{'
主题文件(位于~/assets/themes/dark.scss
中)
ActionBar {
background-color: #B20000;
color: #FFFFFF;
}
.btn-primary {
background-color: #B20000;
color: #000000;
}
函数applyThemeCss()
应该从项目中提取样式,但这不是因为错误。
可以找到测试项目here, on StackBlitz(我没有使用Nativescript游乐场,因为它没有package.json和Assets文件夹)
答案 0 :(得分:1)
applyThemeCss()
期望CSS文本不是文件路径。在示例代码中,他使用require语句读取文件,然后将CSS文本传递给方法。
同样,如果您希望动态应用多个主题,则可能必须修改webpack.config.js
才能将CSS文件发送到应用程序包,如下所示。
// Copy assets to out dir. Add your own globs as needed.
new CopyWebpackPlugin([
{ from: { glob: "assets/**" } },
{ from: { glob: "fonts/**" } },
{ from: { glob: "**/*.jpg" } },
{ from: { glob: "**/*.png" } },
], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }),
然后使用applyTheme()
方法传递文件名
Themes.applyTheme(ThemeService.THEME_PATH + theme);
如果您想使用applyThemeCss()
,请阅读文件并传递内容
Themes.applyThemeCSS(knownFolders.currentApp().getFile('assets/themes/' + theme).readTextSync(), theme);
答案 1 :(得分:0)
在@Manoj的帮助下,我设法将CSS主题加载到应用程序中并切换了主题。
第{ from: { glob: "assets/**" } },
行将样式表从'assets /'复制到'dist / assets'。
但是,由于我想将所有样式保留在同一文件夹(“ styles /”)中,因此需要将代码更新为:{ from: { glob: "styles/themes/**" }, to: 'assets/' },
。
并且由于我使用的是scss而不是css,所以我仍然需要转换样式。我们可以通过node-sass的renderSync
方法来做到这一点。 (有关更多信息,请参见this post)
当我们结合使用此代码时,将得到以下代码:
const scss = require('node-sass');
....
new CopyWebpackPlugin([
{
from: { glob: "styles/themes/*.scss" },
to: 'assets/themes/[name].css',
transform(content, path) {
const result = sass.renderSync({ file: path });
return result.css.toString();
},
},
{from: {glob: "fonts/**"}},
{from: {glob: "**/*.jpg"}},
{from: {glob: "**/*.png"}},
], {ignore: [`${relative(appPath, appResourcesFullPath)}/**`]}),
这会将主题文件从styles/themes/
复制并编译到assets/themes/
。请注意,这也将忽略位于主题文件夹中的所有子文件夹。这样,我们可以执行以下操作:
themes/
-- parts/ // <-- This folder will not be copied
---- _dark-variables.scss
---- _light-variables.scss
-- dark.scss // <-- This will be compiled into assets/themes/dark.css
-- light.scss // <-- This will be compiled into assets/themes/light.css