Advanced use: compile front-end resources through Laravel Mix
brief introduction
Laravel Mix A set of streaming APIs is provided, and some common CSS and JavaScript preprocessors are used to define the Webpack construction steps for Laravel applications. With a simple method chain, you can define the resource pipeline in a streaming manner. For example:
mix.js('resources/assets/js/app.js', 'public/js') .sass('resources/assets/sass/app.scss', 'public/css');
If you are confused about how to start compiling with Webpack and front-end resources, you will fall in love with Larravel Mix. However, it is not mandatory to use it during development. You can choose to use any front-end resource pipeline tool or not at all.
Install&Setup
Installing the Node
Before starting to contact Mix, you must first ensure that Node.js and NPM have been installed on the machine:
node -v npm -v
By default, Larravel Homestead already contains everything you need; However, if you do not use Homestead, you can also access Node download page Easily download and install the latest version of Node and NPM.
Laravel Mix
Next, you need to install Laravel Mix. In the newly installed Laravel root directory, you will find a package.json
File. This file contains everything you need, and composer.json
Similarly, it is only used to define node dependencies rather than PHP dependencies. You can install the required dependencies by running the following command:
npm install
If you are developing on a Windows system, you need to run npm install
On command --no-bin-links
:
npm install --no-bin-links
Run Mix
Mix is located in Webpack The top configuration layer, so you only need to run the Mix task in the default package.json
One of the NPM scripts in the file can:
//Run All Mix Tasks npm run dev //Run all Mix tasks and reduce output npm run production
Monitor changes in front-end resources
npm run watch
The command will continue to run on the terminal and listen to the modification of all related files. Webpack will automatically recompile the resource file after finding the modification:
npm run watch
You may find that the specific environment's Webpack will not be updated when the file changes. If you encounter such a problem, you can consider using watch-poll
Command:
npm run watch-poll
Working with Style Sheets
webpack.mix.js
It is the entry point for all resource compilation and can be regarded as the lightweight configuration encapsulation layer of Webpack. Mix tasks can be chained together in the way of method chain to define how front-end resources are compiled.
Less
To set Less Compiled into CSS, you can use less
method. Let's compile app.less
File to public/css/app.css
:
mix.less('resources/assets/less/app.less', 'public/css');
Multiple calls less
Method can be used to compile multiple files:
mix.less('resources/assets/less/app.less', 'public/css') .less('resources/assets/less/admin.less', 'public/css');
If you want to customize the output location of the compiled file, you can pass the complete path information as the second parameter to less
method:
mix.less('resources/assets/less/app.less', 'public/stylesheets/styles.css');
If you need to overwrite Bottom Level Less Plug in Options , you can pass an object as mix.less()
Third parameter of:
mix.less('resources/assets/less/app.less', 'public/css', { strictMath: true });
Sass
sass
Method allows you to Sass Compile into CSS. You can use this method like this:
mix.sass('resources/assets/sass/app.scss', 'public/css');
Similarly, and less
In the same way, you can compile multiple Sass files into a single CSS file, or even customize the output path of the result CSS:
mix.sass('resources/assets/sass/app.sass', 'public/css') .sass('resources/assets/sass/admin.sass', 'public/css/admin');
excess Node Sass plug-in options It can be provided in the form of the third parameter:
mix.sass('resources/assets/sass/app.sass', 'public/css', { precision: 5 });
Stylus
Similar to Less and Sass, stylus
Method allows you to Stylus Compile into CSS:
mix.stylus('resources/assets/stylus/app.styl', 'public/css');
You can also install additional Stylus plug-ins, such as Rupture First, install the plug-in through NPM( npm install rupture
)Then call mix.stylus()
Introduce it when:
mix.stylus('resources/assets/stylus/app.styl', 'public/css', { use: [ require('rupture')() ] });
PostCSS
PostCSS , is a powerful tool for converting CSS, and can be used out of the box in Laravel Mix. By default, Mix uses the popular Autoprefixer Plug in to automatically add the required CSS3 browser engine prefix. However, you can also add other additional plug-ins suitable for the application. First, install the required plug-ins through NPM, and then click webpack.mix.js
References in documents:
mix.sass('resources/assets/sass/app.scss', 'public/css') .options({ postCss: [ require('postcss-css-variables')() ] });
Native CSS
If you only want to merge multiple native CSS style files into one file, you can use styles
method:
mix.styles([ 'public/css/vendor/normalize.css', 'public/css/vendor/videojs.css' ], 'public/css/all.css');
URL processing
Since Laravel Mix is developed based on Webpack, it is important to understand a little about the concept of Webpack. For CSS compilation, Webpack will rewrite and optimize all url() calls in the stylesheet. Although this may sound strange at first, it is really a powerful function. Suppose we want to compile Sass containing image relative URLs:
.example { background: url('../ images/example.png'); }
Note: Any given url()
The absolute path of will be excluded from URL rewriting, for example, url('/images/thing.png')
or url(' http://example.com/images/thing.png ')
Will not be modified.
By default, Larravel Mix and Webpack will find example.png
, copy it to public/images
Directory, and then override it in the generated stylesheet url()
Therefore, the compiled CSS is as follows:
.example { background: url(/images/example.png? d41d8cd98f00b204e9800998ecf8427e); }
As useful as this function is, the existing directory structure may have been configured in the way you want. In this case, you can disable url()
rewrite:
mix.sass('resources/assets/app/app.scss', 'public/css') .options({ processCssUrls: false });
If this configuration is added to webpack.mix.js
Files, Mix will no longer match url()
Or copy resources to public
catalog. In other words, the compiled CSS is the same as the one entered before compilation:
.example { background: url("../images/thing.png"); }
Source Map
Although Source Map is disabled by default, you can use the webpack.mix.js
Called in file mix.sourceMaps()
To activate. Although this may cause compilation/performance overhead, additional debugging information can be provided to the browser's developer tools when compiling resources:
mix.js('resources/assets/js/app.js', 'public/js') .sourceMaps();
Working with JavaScript
Mix also provides several features to help you process JavaScript files, such as compiling ECMAScript 2015, module bundling, minimizing, and merging native JavaScript files. What's more, these are all seamlessly integrated, and no additional custom configuration is required:
mix.js('resources/assets/js/app.js', 'public/js');
With this line of code, you can use the following functions:
- ES2015 Syntax
- modular
- compile
.vue
file
- Minimize production environment
Extract Vendor Library
A potential disadvantage of bundling all application specific JavaScript and vendor libraries is that long-term caching will become more difficult. For example, a single update of application code will force the browser to download all vendor libraries, even if they are not updated.
If you want to update the JavaScript of the application frequently, you need to consider extracting and splitting the vendor library, so that a change to the application code will not affect vendor.js
Cache of files. Mix's extract
The method can realize the following functions:
mix.js('resources/assets/js/app.js', 'public/js') .extract(['vue'])
extract
Method receives an array containing all libraries or you want to extract vendor.js
Using the above code as an example, Mix will generate the following files:
-
public/js/manifest.js
: Webpack manifest runtime
-
public/js/vendor.js
: Vendor library
-
public/js/app.js
: Application code
To avoid JavaScript errors, ensure that these files are loaded in the correct order:
<script src="/js/manifest.js"></script> <script src="/js/vendor.js"></script> <script src="/js/app.js"></script>
React
Mix can automatically install the Babel plug-in to support React. We can mix.js()
Call replaced with mix.react()
To achieve:
mix.react('resources/assets/js/app.jsx', 'public/js');
Behind this scenario, Mix will download and introduce the appropriate Babel plug-in babel-preset-react
。
Vanilla JS
And use mix.styles()
Merging style sheets is similar. You can use scripts()
Method to merge and minimize any number of JavaScript files:
mix.scripts([ 'public/js/admin.js', 'public/js/dashboard.js' ], 'public/js/all.js');
This function is very useful for traditional applications that do not need Webpack to compile Javascript.
Note: mix.scripts()
A slight adjustment of mix.babel()
, its method signature and scripts
Similarly, the difference is that the merged file will be compiled by Babel, thus converting all ES2015 code into native JavaScript supported by all browsers.
Customize Webpack Configuration
Behind the scene, Laravel Mix references the preconfigured webpack.config.js
File to start and run as fast as possible. In some cases, you need to edit the file manually. You may have a specific loader or plug-in referenced, or you may prefer to use Stylus instead of Sass. In these cases, you have two choices:
Merge Custom Configurations
Mix provides a useful webpackConfig
Method, which allows you to merge any short Webpack configuration overrides. This is an attractive choice because you don't need to copy or maintain your own webpack.config.js
Copies of documents, webpackConfig
Method receives an object that contains any object you want to apply Webpack Specify Configuration :
mix.webpackConfig({ resolve: { modules: [ path.resolve(__dirname, 'vendor/laravel/spark/resources/assets/js') ] } });
Custom Profile
The second option is to copy Mix's webpack.config.js
To your own project root directory:
cp node_modules/laravel-mix/setup/webpack.config.js ./
Next package.json
All in file --config
The reference points to the copied new configuration file. If you choose to use this custom method, you can only use Mix's webpack.config.js
If there are upgrade changes, manually merge the changes into the new customized file.
Copy files/directories
You can use copy
Method to copy the file/directory to a new path, which will node_modules
The specific resource files under the directory are relocated to public
It is useful when under the directory:
mix.copy('node_modules/foo/bar.css', 'public/css/bar.css');
When copying directories, copy
Method will flatten the directory structure. To maintain the original structure of the directory, you need to use the copyDirectory
method:
mix.copyDirectory('assets/img', 'public/img');
Version number/cache refresh
Many developers will add a timestamp or unique token suffix to the compiled front-end resources to force the browser to load the latest version instead of the cached copy of the code. Mix can use version
Method handles this scenario for you.
version
Method will automatically append a unique hash to the compiled file name to facilitate cache refresh:
mix.js('resources/assets/js/app.js', 'public/js') .version();
After the version file is generated, the extracted file name is unknown, so you need to view Using Laravel global mix
Function to load the corresponding front-end resources with hash values. mix
The function will automatically determine the current hashed file name:
<link rel="stylesheet" href="{{ mix('css/app.css') }}">
Because the version file is useless in local development, you can only run npm run production
Version processing during:
mix.js('resources/assets/js/app.js', 'public/js'); if (mix.config.inProduction) { mix.version(); }
BrowserSync Reload
BrowserSync It will automatically monitor file modifications and inject them into the browser without manual refresh. You can enable this support by calling the mix. browserSync() method:
mix.browserSync('my-domain.test'); // Or... // https://browsersync.io/docs/options mix.browserSync({ proxy: 'my-domain.test' });
You can pass a string (proxy) or object (BrowserSync settings) to this method. Next, use the npm run watch
Command to start the Webpack development server. Now, when you edit a JavaScript script or PHP file, you will see that the browser will immediately refresh to respond to your changes.
environment variable
You can use the .env
Document file addition MIX_
Prefix injects environment variables into Mix:
MIX_SENTRY_DSN_PUBLIC= http://example.com
stay .env
After defining variables in the file, you can use the process.env
Object (if running watch
The variable value changes during the task, and the task needs to be restarted):
process.env.MIX_SENTRY_DSN_PUBLIC
notice
If it works, Mix will automatically display the operating system notification for each bundle, which can give you a timely feedback: compilation success or failure. However, in some scenarios, you may want to disable these notifications. A typical example is that Mix is triggered on the production environment server. Notification can be made through disableNotifications
Method disabled:
mix.disableNotifications();