laravel mix

tech2022-08-19  72

laravel mix

This article was peer reviewed by Younes Rafie, Wern Ancheta, and Christopher Pitt. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

这篇文章由Younes Rafie , Wern Ancheta和Christopher Pitt进行了同行评审。 感谢所有SitePoint的同行评审人员使SitePoint内容达到最佳状态!



If you, like me, just want to get up and running on a project as quickly as possible, you probably don’t want to spend time configuring build tools like Webpack. Laravel Mix solves this problem, and makes asset compiling incredibly easy, but what if you want to use it on a non-Laravel project? This article shows you how to accomplish that.

如果像我一样,您只想尽快启动并运行一个项目,则可能不想花时间配置Webpack等构建工具。 Laravel Mix解决了这个问题,并使资产编译变得异常容易,但是如果您想在非Laravel项目中使用它,该怎么办? 本文向您展示了如何实现这一目标。

什么是Laravel Mix? (What Is Laravel Mix?)

Laravel Mix, formerly Elixir, could be defined as an API wrapper for Webpack. It has a fluent syntax and is generally easy to use. Setting up versioning, hot reloading, and asset building/compiling is a breeze, and requires only a single configuration file and a few lines of code.

Laravel Mix,以前是Elixir,可以定义为Webpack的API包装器。 它具有流利的语法,并且通常易于使用。 设置版本控制,热重装和资产构建/编译非常容易,并且只需要一个配置文件和几行代码。

背景故事 (Backstory)

For most of my projects, be it clients or personal, I choose Laravel, but I recently had a client who wanted the ability to edit pages and content on their website, he wanted a CMS. I decided to give OctoberCMS a try, considering that it’s based on Laravel.

对于我的大多数项目,无论是客户还是个人项目,我都选择Laravel ,但最近我有一位希望在其网站上编辑页面和内容的功能的客户,他需要CMS。 我决定给OctoberCMS一试,考虑到它是基于Laravel。

I set up File Watchers from PhpStorm, but it didn’t work as well as running Laravel Mix. After a week of using File Watchers, I tried pulling Laravel Mix from a Laravel project, and the result feels exactly like it should.

我从PhpStorm设置了File Watchers,但是运行Laravel Mix并不能正常工作。 在使用File Watchers一周后,我尝试从Laravel项目中提取Laravel Mix,结果感觉完全一样。

要求 (Requirements)

For this tutorial, I assume that you have basic knowledge of managing JSON files and that you have NPM and Node installed on your system.

对于本教程,我假设您具有管理JSON文件的基本知识,并且已在系统上安装了NPM和Node 。

If you want to use versioning and hot reload, you’re required to use PHP, and Composer.

如果要使用版本控制和热重装,则需要使用PHP和Composer 。

To verify that you have NPM and Node, you can run the following in your terminal:

要验证您是否具有NPM和Node,可以在终端中运行以下命令:

node -v npm -v

You should see versions for both Node and NPM.

您应该看到Node和NPM的版本。

Note: You can also use Homestead Improved which comes with all of this installed. If that’s confusing to you, clear things up with our book!

注意:您也可以使用所有安装的Homestead Improvementd 。 如果这让您感到困惑,请清除我们的书!

入门 (Getting Started)

Start by launching your favorite terminal/console application.

首先启动您喜欢的终端/控制台应用程序。

If you don’t already have a project and want to start off on an empty one, simply create an empty directory somewhere on your computer, and use it as your project directory. You don’t need any initial files to get started.

如果您还没有项目,并且想从一个空的项目开始,只需在计算机上的某个地方创建一个空目录,然后将其用作项目目录。 您不需要任何初始文件即可开始。

安装Laravel Mix和SASS (Install Laravel Mix and SASS)

You’ll now be installing Laravel Mix, but you also need another dependency called “cross-env”, to be able to use environment variables across different platforms. Also, you’ll need “node-sass” to compile SASS files.

现在,您将安装Laravel Mix,但是您还需要另一个名为“ cross-env”的依赖项,以便能够在不同平台上使用环境变量。 另外,您将需要“ node-sass”来编译SASS文件。

To install Laravel Mix, SASS and cross-env, run the following command:

要安装Laravel Mix,SASS和cross-env,请运行以下命令:

npm install laravel-mix cross-env node-sass --save-dev

If everything works correctly, you will have a new directory named node_modules, and your package.json file will have been updated as well.

如果一切正常,您将拥有一个名为node_modules的新目录,并且package.json文件也将被更新。

Remember to add node_modules to your .gitignore file, if you’re going to version control your work.

如果要进行版本控制,请记住将node_modules添加到.gitignore文件中。

创建一个Webpack混合文件 (Creating a Webpack Mix File)

With Laravel Mix, you won’t have to worry about creating a Webpack config file, which is my main reason for using it in almost all web projects. You’ll only have to create a file that defines which assets you want compiled.

使用Laravel Mix,您不必担心创建Webpack配置文件,这是我在几乎所有Web项目中使用它的主要原因。 您只需要创建一个文件即可定义要编译的资产。

Start by creating a new file named webpack.mix.js in your project’s root. Add the following content to it:

首先在项目的根目录中创建一个名为webpack.mix.js的新文件。 向其中添加以下内容:

const mix = require('laravel-mix'); mix.js('resources/js/app.js', 'public/js') .sass('resources/sass/app.scss', 'public/css');

This defines a Javascript file and a SCSS/SASS file that you want to compile using Webpack, and the output directories. You can set the files and output names as you desire. I’ll call the mix.js(..).sass(..) code a “mix chain” for the purpose of this tutorial.

这定义了要使用Webpack编译的Javascript文件和SCSS / SASS文件,以及输出目录。 您可以根据需要设置文件和输出名称。 在本教程中,我将mix.js(..).sass(..)代码称为“混合链”。

将脚本添加到package.json (Add Scripts to package.json)

To actually use Mix, you’ll have to include some scripts in your package.json file. For the purpose of keeping it as similar to Laravel as possible, I decided to copy them directly from a new Laravel 5.4 project.

要实际使用Mix,您必须在package.json文件中包含一些脚本。 为了尽可能使其与Laravel相似,我决定直接从新的Laravel 5.4项目中复制它们。

If you already have a scripts variable in your file, you can remove its contents.

如果文件中已包含脚本变量,则可以删除其内容。

Open up your package.json file in your code editor, and add the scripts and config variables, with this content:

在代码编辑器中打开package.json文件,并添加scripts和config变量,内容如下:

"scripts": { "dev": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", "watch": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", "hot": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js", "production": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js" },

Your file should look similar to this.

您的文件应与此类似。

创建要编译的资产 (Creating Assets to Be Compiled)

In your webpack.mix.js file, we defined some files to compile, but chances are that these files don’t exist if it’s a new project. You want your folder structure to look similar to this:

在您的webpack.mix.js文件中,我们定义了一些要编译的文件,但是如果这是一个新项目,则可能这些文件不存在。 您希望文件夹结构看起来像这样:

You can add some content to your resources/sass/app.sass file for testing:

您可以将一些内容添加到resources/sass/app.sass文件中以进行测试:

body { background: red; }

运行Laravel Mix (Run Laravel Mix)

To test if everything works as expected, run the following command:

要测试是否一切正常,请运行以下命令:

npm run dev

You should see a screen similar to this:

您应该看到类似于以下的屏幕:

设置缓存清除和热重载 (Set up Cache Busting and Hot Reload)

Hot reloading allows you to tweak your assets and have changes instantly appear in your browser, without actually refreshing. This is particularly useful for CSS adjustments. It automatically injects the latest version of your files on each change.

热重载使您可以调整资产,并使更改立即显示在浏览器中,而无需实际刷新。 这对于CSS调整特别有用。 每次更改时,它都会自动注入文件的最新版本。

Laravel Mix uses BrowserSync for this, which also comes with a lot of neat features such as the ability to view the content on other devices and synchronize state (input, scroll and more) between devices.

Laravel Mix为此使用了BrowserSync,它还具有许多简洁的功能,例如能够查看其他设备上的内容以及在设备之间同步状态(输入,滚动等)的功能。

Cache busting is a way to avoid browser cache by adding hashes to compiled assets, so app.js might turn into app.b2328beb0372c051d06d.js. This forces the browser to fetch the file from the server.

缓存清除是通过向已编译资产中添加哈希来避免浏览器缓存的一种方法,因此app.js可能会变成app.b2328beb0372c051d06d.js 。 这将强制浏览器从服务器获取文件。

To set up cache busting and hot reloading, we will have to include a php file that provides the same mix() method (which you might know from Laravel).

要设置缓存清除和热重载,我们将必须包括一个提供相同mix()方法的php文件(您可能会从Laravel中知道)。

The mix() method is a basic helper which finds the correct version of your assets, and figures out if hot reloading is enabled.

mix()方法是一个基本的帮助程序,它可以找到资产的正确版本,并确定是否启用了热重装。

Create a file named mix.php in your project root (or where ever you’d prefer it to be) with the following content:

在项目根目录(或您希望使用的目录)中创建一个名为mix.php的文件,内容如下:

<?php if (! function_exists('mix')) { /** * Get the path to a versioned Mix file. * * @param string $path * @param string $manifestDirectory * @return string * * @throws \Exception */ function mix($path, $manifestDirectory = '') { static $manifest; $publicFolder = '/public'; $rootPath = $_SERVER['DOCUMENT_ROOT']; $publicPath = $rootPath . $publicFolder; if ($manifestDirectory && ! starts_with($manifestDirectory, '/')) { $manifestDirectory = "/{$manifestDirectory}"; } if (! $manifest) { if (! file_exists($manifestPath = ($rootPath . $manifestDirectory.'/mix-manifest.json') )) { throw new Exception('The Mix manifest does not exist.'); } $manifest = json_decode(file_get_contents($manifestPath), true); } if (! starts_with($path, '/')) { $path = "/{$path}"; } $path = $publicFolder . $path; if (! array_key_exists($path, $manifest)) { throw new Exception( "Unable to locate Mix file: {$path}. Please check your ". 'webpack.mix.js output paths and try again.' ); } return file_exists($publicPath . ($manifestDirectory.'/hot')) ? "http://localhost:8080{$manifest[$path]}" : $manifestDirectory.$manifest[$path]; } }

让我们使用Composer自动加载它。 (Let’s Autoload It with Composer.)

Open up your composer.json file, or create a new one in your project’s root.

打开您的composer.json文件,或在项目的根目录中创建一个新文件。

We want to automatically load mix.php before all PHP requests. Add the following:

我们希望在所有PHP请求之前自动加载mix.php 。 添加以下内容:

{ ... "autoload": { "files": ["mix.php"] } ... }

Your file should be similar to this one.

您的文件应与此文件相似。

设置索引文件以测试资产 (Set up an Index File for Testing Your Assets)

To actually test if the versioning works, we’ll have to version our assets (and optionally enable hot reloading), so head over to your webpack.mix.js file and change it to:

要实际测试版本管理是否webpack.mix.js ,我们必须对资产进行版本控制(并可以选择启用热重装),因此请转到您的webpack.mix.js文件并将其更改为:

const mix = require('laravel-mix'); mix.js('resources/js/app.js', 'public/js') .sass('resources/sass/app.scss', 'public/css') .version() .browserSync(); // Hot reloading

You want it to look something like this.

您希望它看起来像这样 。

Now, create an index.php file for the purpose of testing the assets, and add some demo content:

现在,创建一个index.php文件以测试资产,并添加一些演示内容:

<?php require_once 'vendor/autoload.php'; ?> <!DOCTYPE html> <html> <head> <title>Demo</title> <link rel="stylesheet" href="<?php echo mix('css/app.css'); ?>" /> </head> <body> Hello world. <script src="<?php echo mix('js/app.js'); ?>"></script> </body> </html> Go to your project root directory in the terminal / command line.

在终端/命令行中转到您的项目根目录。

如果要热装 (If You Want Hot Reloading)

Run npm run hot in your terminal to generate versioned assets and initialize hot reloading. A webpage should now open, showing your site. If you chose this step, you can skip the next sub-section.

在终端中运行npm run hot来生成版本化资产并初始化热重装。 现在应该打开一个网页,显示您的站点。 如果选择了此步骤,则可以跳过下一部分。

如果您不想热装 (If You Don’t Want Hot Reloading)

Run the following command:

运行以下命令:

npm run dev

Now run the following command:

现在运行以下命令:

php -S localhost:8080

This starts a PHP server.

这将启动一个PHP服务器。

Open your browser and navigate to the site’s URL with the port 8080, e.g. homestead.app:8080

打开浏览器,并使用端口8080导航到站点的URL,例如homestead.app:8080

结果 (Result)

You should see a red background (if you decided to keep the body styling in your app.scss file)

您应该看到红色背景(如果您决定将主体样式保留在app.scss文件中)

That’s it! You now have a very flexible Webpack configuration using Laravel Mix, without Laravel itself. Be sure to check out the Laravel Mix documentation.

而已! 您现在有了使用Laravel Mix的非常灵活的Webpack配置,而无需Laravel本身。 请务必查看Laravel Mix文档 。

附加命令 (Additional commands)

In your package.json file, there are actually two more scripts/commands: production and watch. Both could prove to be very useful for your workflow.

在package.json文件中,实际上还有两个脚本/命令: production和watch 。 两者都可能对您的工作流程非常有用。

production指令 (The production command)

When you’re ready to deploy your project to production, you’ll want to generate minified assets, which is exactly what the production command does. You run it like this:

当您准备将项目部署到生产中时,您将希望生成精简资产,这正是production命令所要做的。 您可以这样运行它:

npm run production

Minified production assets should now have been generated.

现在应该已经生成了小型生产资产。

watch命令 (The watch command)

Running dev for each minor change to your scripts or styling would quickly become a pain. watch helps with this. What this command does is monitor your files for changes and compile the assets again if changes are detected.

对脚本或样式的每一次微小更改运行dev都会很快变得很痛苦。 watch对此有帮助。 该命令的作用是监视文件中的更改,并在检测到更改时再次编译资产。

npm run watch

Please note that it can be harder to diagnose build errors (especially JS syntax errors) with the watch command running. If you run into problems, run the dev command for clearer output.

请注意,使用watch命令运行时,可能很难诊断出构建错误(尤其是JS语法错误)。 如果遇到问题,请运行dev命令以获得更清晰的输出。

结论 (Conclusion)

If you’re not interested in following the process and simply want to get started right away, you can go to the Github repository, and look at the example project.

如果您对遵循该过程不感兴趣,只是想立即开始,则可以转到Github存储库 ,并查看示例项目。

To me, this is the optimal way to use Laravel Mix on smaller projects where I’m not using Laravel. After getting used to this flow, setting it up takes only a few minutes, whereas configuring Webpack takes far longer.

对我来说,这是在我不使用Laravel的较小项目上使用Laravel Mix的最佳方法。 习惯了此流程之后,对其进行设置仅需几分钟,而配置Webpack则需要更长的时间。

Do you agree/disagree? Do you use pure webpack, or another bundler/builder in your PHP projects? Let us know in the comments!

你同意/不同意吗? 您是否在PHP项目中使用纯webpack或其他捆绑程序/生成器? 让我们在评论中知道!

翻译自: https://www.sitepoint.com/use-laravel-mix-non-laravel-projects/

laravel mix

最新回复(0)