magento启用前端grunt编译,加快开发进度
一、后端编译方式
在magento前端开发过程中,在修改前端样式后,是需要经过编译才能生成相应的前端样式生效于页面,在一般情况下,我们是使用静态内容部署进行处理,如下代码:
sudo rm -rf pub/static/frontend/* var/view_preprocessed/* var/cache/* var/page_cache/* && \
php7.2 bin/magento setup:static-content:deploy -f && \
php7.2 bin/magento cache:clean && \
php7.2 bin/magento cache:flush
二、前端grunt编译方式
除了后端方式,还有一种前端的方式,具体如下
1. 启用 Grunt 的前提条件
在开始之前,确保满足以下条件:
Node.js 和 npm:Grunt 依赖 Node.js 和 npm(Node.js 包管理器)。
node -v
npm -v
#如果没有安装,则使用如下命令进行安装
sudo apt install node.js
sudo apt install npm
sudo npm install -g grunt-cli
Magento 2 项目:确保你已经有一个 Magento 2 项目,并且项目根目录下有 package.json
和 Gruntfile.js
文件。
2. 配置 Grunt环境
2.1 安装grunt依赖
在 Magento 2 项目根目录下运行以下命令,安装 Grunt 所需的依赖:
cp package.json.sample package.json
cp grunt-config.json.sample grunt-config.json
cp Gruntfile.js.sample Gruntfile.js
#以上3个命令为复制基础配置文件
npm install
#执行安装grunt必要的包
2.2 确认主题
在 app/design/frontend/<Vendor>/<Theme>/requirejs-config.js
或 app/design/frontend/<Vendor>/<Theme>/web/css/source/_theme.less
中,确保你的主题已正确配置。
2.4 配置 Grunt 主题映射
编辑 dev/tools/grunt/configs/themes.js
文件,将你的主题添加到 Grunt 的配置中。
#将以下文件加进去
module.exports = {
<Vendor>: {
area: 'frontend',
name: '<Vendor>/<Theme>',
locale: 'en_US',
files: [
'css/styles-m',
'css/styles-l'
],
dsl: 'less'
}
};
将 <Vendor>/<Theme>
替换为你的实际命名空间/主题名称。
<Vendo>是app/design/frontend/的主题目录名
,magento后台用哪个命名空间主题,这里面就写对应的目录名称。
<Vendor>/<Theme>
是app/design/frontend/
<Vendo>的主题目录名
,magento后台用哪个主题,这里面就写对应的目录名称。
3. 在 Magento 后台开启前端编译设置
3.1 登录 Magento 后台
进入 Magento 后台管理页面。
3.2 进入前端编译设置
- 导航到 Stores > Configuration。
- 在左侧菜单中,选择 Advanced > Developer。
- 在 Developer 设置页面中,找到 Front-end development workflow 部分。
3.3 设置前端编译模式
将 Front-end development workflow 设置为 Client side less compilation 或 Server side less compilation。
- Client side less compilation:适用于开发环境,使用浏览器实时编译 LESS 文件。
- Server side less compilation:适用于生产环境,使用 Grunt 或 Magento 内置工具编译 LESS 文件。
1.4 保存配置
点击 Save Config 保存设置。
4. 使用 Grunt 编译前端资源
#!/bin/bash
sudo php7.2 bin/magento cache:clean
sudo grunt clean:Vendor
sudo grunt exec:Vendor
sudo grunt less:Vendor
4.1 命令解释
grunt clean:清理之前生成的静态文件
grunt exec:将主题文件复制到 pub/static/frontend/<Vendor>/<Theme>
目录。grunt less:将 LESS 文件编译为 CSS 文件。