Hướng dẫn code js dùng laravel mix năm 2024
Version Show
WARNING You're browsing the documentation for an old version of Laravel. Consider upgrading your project to Laravel 10.x. Compiling Assets (Mix)IntroductionLaravel Mix, a package developed by Laracasts creator Jeffrey Way, provides a fluent API for defining webpack build steps for your Laravel application using several common CSS and JavaScript pre-processors. In other words, Mix makes it a cinch to compile and minify your application's CSS and JavaScript files. Through simple method chaining, you can fluently define your asset pipeline. For example:
If you've ever been confused and overwhelmed about getting started with webpack and asset compilation, you will love Laravel Mix. However, you are not required to use it while developing your application; you are free to use any asset pipeline tool you wish, or even none at all. {tip} If you need a head start building your application with Laravel and Tailwind CSS, check out one of our application starter kits. Installation & SetupInstalling NodeBefore running Mix, you must first ensure that Node.js and NPM are installed on your machine:
You can easily install the latest version of Node and NPM using simple graphical installers from the official Node website. Or, if you are using Laravel Sail, you may invoke Node and NPM through Sail:
Installing Laravel MixThe only remaining step is to install Laravel Mix. Within a fresh installation of Laravel, you'll find a
0 file in the root of your directory structure. The default
0 file already includes everything you need to get started using Laravel Mix. Think of this file like your
2 file, except it defines Node dependencies instead of PHP dependencies. You may install the dependencies it references by running:
Running MixMix is a configuration layer on top of webpack, so to run your Mix tasks you only need to execute one of the NPM scripts that are included in the default Laravel
0 file. When you run the
4 or
5 scripts, all of your application's CSS and JavaScript assets will be compiled and placed in your application's
6 directory:
Watching Assets For ChangesThe
7 command will continue running in your terminal and watch all relevant CSS and JavaScript files for changes. Webpack will automatically recompile your assets when it detects a change to one of these files:
Webpack may not be able to detect your file changes in certain local development environments. If this is the case on your system, consider using the
8 command:
Working With StylesheetsYour application's
9 file is your entry point for all asset compilation. Think of it as a light configuration wrapper around webpack. Mix tasks can be chained together to define exactly how your assets should be compiled. Tailwind CSSTailwind CSS is a modern, utility-first framework for building amazing sites without ever leaving your HTML. Let's dig into how to start using it in a Laravel project with Laravel Mix. First, we should install Tailwind using NPM and generate our Tailwind configuration file:
The
0 command will generate a
1 file. The
2 section of this file allows you to configure the paths to all of your HTML templates, JavaScript components, and any other source files that contain Tailwind class names so that any CSS classes that are not used within these files will be purged from your production CSS build:
Next, you should add each of Tailwind's "layers" to your application's
3 file:
Once you have configured Tailwind's layers, you are ready to update your application's
9 file to compile your Tailwind powered CSS:
0 Finally, you should reference your stylesheet in your application's primary layout template. Many applications choose to store this template at
5. In addition, ensure you add the responsive viewport
6 tag if it's not already present:
1 PostCSSPostCSS, a powerful tool for transforming your CSS, is included with Laravel Mix out of the box. By default, Mix leverages the popular Autoprefixer plugin to automatically apply all necessary CSS3 vendor prefixes. However, you're free to add any additional plugins that are appropriate for your application. First, install the desired plugin through NPM and include it in your array of plugins when calling Mix's
7 method. The
7 method accepts the path to your CSS file as its first argument and the directory where the compiled file should be placed as its second argument:
2 Or, you may execute
7 with no additional plugins in order to achieve simple CSS compilation and minification:
3 SassThe
0 method allows you to compile Sass into CSS that can be understood by web browsers. The
0 method accepts the path to your Sass file as its first argument and the directory where the compiled file should be placed as its second argument:
4 You may compile multiple Sass files into their own respective CSS files and even customize the output directory of the resulting CSS by calling the
0 method multiple times:
5 URL ProcessingBecause Laravel Mix is built on top of webpack, it's important to understand a few webpack concepts. For CSS compilation, webpack will rewrite and optimize any
3 calls within your stylesheets. While this might initially sound strange, it's an incredibly powerful piece of functionality. Imagine that we want to compile Sass that includes a relative URL to an image:
6 {note} Absolute paths for any given By default, Laravel Mix and webpack will find
7, copy it to your
8 folder, and then rewrite the
3 within your generated stylesheet. As such, your compiled CSS will be:
7 As useful as this feature may be, your existing folder structure may already be configured in a way you like. If this is the case, you may disable
3 rewriting like so:
8 With this addition to your
9 file, Mix will no longer match any
3 or copy assets to your public directory. In other words, the compiled CSS will look just like how you originally typed it:
9 Source MapsThough disabled by default, source maps may be activated by calling the
3 method in your
9 file. Though it comes with a compile/performance cost, this will provide extra debugging information to your browser's developer tools when using compiled assets:
0 Style Of Source MappingWebpack offers a variety of . By default, Mix's source mapping style is set to
5, which provides a fast rebuild time. If you want to change the mapping style, you may do so using the
6 method:
1 Working With JavaScriptMix provides several features to help you work with your JavaScript files, such as compiling modern ECMAScript, module bundling, minification, and concatenating plain JavaScript files. Even better, this all works seamlessly, without requiring an ounce of custom configuration:
2 With this single line of code, you may now take advantage of:
VueMix will automatically install the Babel plugins necessary for Vue single-file component compilation support when using the
7 method. No further configuration is required:
3 Once your JavaScript has been compiled, you can reference it in your application:
4 ReactMix can automatically install the Babel plugins necessary for React support. To get started, add a call to the
8 method:
5 Behind the scenes, Mix will download and include the appropriate
9 Babel plugin. Once your JavaScript has been compiled, you can reference it in your application:
4 Vendor ExtractionOne potential downside to bundling all of your application-specific JavaScript with your vendor libraries such as React and Vue is that it makes long-term caching more difficult. For example, a single update to your application code will force the browser to re-download all of your vendor libraries even if they haven't changed. If you intend to make frequent updates to your application's JavaScript, you should consider extracting all of your vendor libraries into their own file. This way, a change to your application code will not affect the caching of your large
0 file. Mix's
1 method makes this a breeze:
7 The
1 method accepts an array of all libraries or modules that you wish to extract into a
0 file. Using the snippet above as an example, Mix will generate the following files:
To avoid JavaScript errors, be sure to load these files in the proper order:
8 Custom Webpack ConfigurationOccasionally, you may need to manually modify the underlying Webpack configuration. For example, you might have a special loader or plugin that needs to be referenced. Mix provides a useful
7 method that allows you to merge any short Webpack configuration overrides. This is particularly appealing, as it doesn't require you to copy and maintain your own copy of the
8 file. The
7 method accepts an object, which should contain any Webpack-specific configuration that you wish to apply.
9 Versioning / Cache BustingMany developers suffix their compiled assets with a timestamp or unique token to force browsers to load the fresh assets instead of serving stale copies of the code. Mix can automatically handle this for you using the
0 method. The
0 method will append a unique hash to the filenames of all compiled files, allowing for more convenient cache busting:
0 After generating the versioned file, you won't know the exact filename. So, you should use Laravel's global
2 function within your views to load the appropriately hashed asset. The
2 function will automatically determine the current name of the hashed file:
1 Because versioned files are usually unnecessary in development, you may instruct the versioning process to only run during
4:
2 Custom Mix Base URLsIf your Mix compiled assets are deployed to a CDN separate from your application, you will need to change the base URL generated by the
2 function. You may do so by adding a
6 configuration option to your application's
7 configuration file:
3 After configuring the Mix URL, The
2 function will prefix the configured URL when generating URLs to assets:
4 Browsersync ReloadingBrowserSync can automatically monitor your files for changes, and inject your changes into the browser without requiring a manual refresh. You may enable support for this by calling the
9 method:
5 BrowserSync options may be specified by passing a JavaScript object to the
00 method:
6 Next, start webpack's development server using the
7 command. Now, when you modify a script or PHP file you can watch as the browser instantly refreshes the page to reflect your changes. Environment VariablesYou may inject environment variables into your
9 script by prefixing one of the environment variables in your
03 file with
04:
7 After the variable has been defined in your
03 file, you may access it via the
06 object. However, you will need to restart the task if the environment variable's value changes while the task is running:
8 NotificationsWhen available, Mix will automatically display OS notifications when compiling, giving you instant feedback as to whether the compilation was successful or not. However, there may be instances when you would prefer to disable these notifications. One such example might be triggering Mix on your production server. Notifications may be deactivated using the
07 method: |