Magento PWA:如何在pwa專案中使用SASS或LESS

當我們從github下載Magento PWA Studio來使用的時候,會發現PWA是直接使用CSS檔案,沒有透過任何的編譯工具。如果您已經習慣使用SASS或LESS來編譯CSS,那你一定很希望能夠在PWA繼續使用你熟悉的工具,要不然光是那些巢狀的CSS選擇器,就可以把人給逼瘋。
這篇文章就是要跟大家分享如何在PWA使用SASS及LESS。
在PWA使用SASS
一、安裝依賴項
yarn add --dev [email protected] [email protected]
為了避免版本衝突,所以我們直接指定版本安裝,如果沒有指定版本,在安裝的時候可能會出現 “Syntax Error: TypeError: this.getOptions is not a function" 這個錯誤訊息。這時候只要移除sass-loader
yarn remove sass-loader
再重新指定版本安裝就可以了。另外node-sass則是為了與sass-loader 10.1.1 才指定了版本
二、編輯 webpack.config.js 並增加一個新的rules
config.plugins = [
...config.plugins,
new DefinePlugin({
/**
* Make sure to add the same constants to
* the globals object in jest.config.js.
*/
POSSIBLE_TYPES: JSON.stringify(possibleTypes),
STORE_NAME: JSON.stringify('Venia')
}),
new HTMLWebpackPlugin({
filename: 'index.html',
template: './template.html',
minify: {
collapseWhitespace: true,
removeComments: true
}
})
];
+
+ config.module.rules.push({
+ test: /\.s[ca]ss$/,
+ use: [
+ 'style-loader',
+ {
+ loader: 'css-loader',
+ options: {
+ modules: true,
+ sourceMap: true,
+ localIdentName: '[name]-[local]-[hash:base64:3]'
+ }
+ },
+ 'sass-loader'
+ ]
+ });
三、在 component 中引用SASS檔案
首先建立一個 myComponent.scss,接著在 component 引用它:
import React from 'react';import defaultClasses from './myComponent.scss';
const MyComponent = () => (
<div className={defaultClasses.root}>
<button className={defaultClasses.button}>My Component</button>
</div>);
export default MyComponent;
在PWA使用LESS
一、安裝依賴項
yarn add --dev less-loader less
二、編輯 webpack.config.js 並增加一個新的rules
config.plugins = [
...config.plugins,
new DefinePlugin({
/**
* Make sure to add the same constants to
* the globals object in jest.config.js.
*/
POSSIBLE_TYPES: JSON.stringify(possibleTypes),
STORE_NAME: JSON.stringify('Venia')
}),
new HTMLWebpackPlugin({
filename: 'index.html',
template: './template.html',
minify: {
collapseWhitespace: true,
removeComments: true
}
})
];
+
+ config.module.rules.push({
+ test: /\.less$/,
+ use: [
+ 'style-loader',
+ {
+ loader: 'css-loader',
+ options: {
+ modules: true,
+ sourceMap: true,
+ localIdentName: '[name]-[local]-[hash:base64:3]'
+ }
+ },
+ 'less-loader'
+ ]
+ });
三、在 component 中引用LESS檔案
首先建立一個 myComponent.less,接著在 component 引用它:
import React from 'react';import defaultClasses from './myComponent.less';
const MyComponent = () => (
<div className={defaultClasses.root}>
<button className={defaultClasses.button}>My Component</button>
</div>);
export default MyComponent;
讀者們學會如何在Magento PWA專案中使用SASS或LESS了嗎?更多Magento相關文章分享,不要錯過歐斯瑞後續的發佈呦!還沒追蹤歐斯瑞FB粉絲團及IG的讀者們,趕緊追蹤就不會漏掉任何新知分享囉!也可以訂閱電子報。有任何問題歡迎與我們聯繫~下次見囉!
參考資料:
https://magento.github.io/pwa-studio/tutorials/enable-sass-less-support/
https://magento.github.io/pwa-studio/technologies/basic-concepts/css-modules/
https://medium.com/officialrajdeepsingh/how-to-add-scss-sass-in-react-js-6615b6e77e56
我要留言