Edit assets Mix
- Install Node
- Laravel Mix
- Run MixUse style sheets
- Stylus
- PostCSS
- Native CSS
- URL processing
- Source code mapping
- Use JavaScript
- Vendor Extraction
- React
- Vanilla JS
- Custom Webpack configuration
- Merge custom configuration
- Custom configuration file
- Environment variables
- Notification
Compile Resources (Mix)
- Introduction
- Installation & Settings
- Run Mix
- Using Style Sheets
- Use JavaScript
- Copy Files & Directories
- Version Control/Cache Clear
- Browsersync Reload
- Environment variables
- Notification
node -v npm -v
By default, Laravel Homestead includes everything you need; but if you use Vagrant, you can also use the easier-to-use graphical installation available fromtheir download page The server installs the latest versions of Node and NPM.
Laravel MixThe only thing left is to install Laravel Mix. In a clean installation of Laravel, thepackage.json
file can be found at the root of the directory structure. The default
package.jsonfile contains everything you need to get started, think of it like a
composer.jsonfile, except it defines dependencies for Node instead of PHP . Install the dependencies it references by running the following command:
npm install
Running Mix
Mix is the top-level configuration of Webpack, so to run the Mix task, you only need to execute one line contained in Laravel's default
package.json
file Script:// 运行 Mix 任务... npm run dev // 运行所有的 Mix 任务并最小化输出结果... npm run production
Listen for resource changes
npm run watch
The command can continue to run in the terminal and monitor changes in related files. Webpack will automatically recompile resources once it detects changes:npm run watch
You will find that in certain circumstances, changing files does not prompt Webpack to update. If this situation occurs in your system, you may wish to consider using the
watch-poll
command:npm run watch-poll
Use style sheets
##Lesswebpack.mix.js
The entry point for compiling all resources in the file. Think of it as a lightweight configuration wrapper for Webpack. Mix tasks can be chained together with configuration of how resources are compiled.less
method can be used to compile
Less into CSS. The following statement compiles the app.lessfile to
public/css/app.css:
mix.less('resources/less/app.less', 'public/css');
can be made by calling theless
method multiple times Complete multi-file compilation:
mix.less('resources/less/app.less', 'public/css') .less('resources/less/admin.less', 'public/css');
If you want to customize the compiled CSS file name, you can pass the complete file path as the second parameter to theless
method:
mix.less('resources/less/app.less', 'public/stylesheets/styles.css');
If you need to override theimplicit Less plug-in option , you can pass an object as the third parameter of mix.less()
:
mix.less('resources/less/app.less', 'public/css', { strictMath: true });
## The#Sasssassmethod compiles
lessSass
into CSS. You can use this method like this:mix.sass('resources/sass/app.scss', 'public/css');
Similar to themethod, you can compile multiple Sass files into their own CSS files and customize the output directory for the resulting CSS:
Node-Sass plugin options
Additionalmix.sass('resources/sass/app.sass', 'public/css') .sass('resources/sass/admin.sass', 'public/css/admin');
are available as the third argument:
mix.sass('resources/sass/app.sass', 'public/css', { precision: 5 });
StylusSimilar to Less and Sass, the
stylusmethod compiles
RuptureStylus
into CSS:mix.stylus('resources/stylus/app.styl', 'public/css');
You can also install additional Stylus plugins, such as. First install the plugin via NPM (npm install rupture), and then include it when calling
mix.stylus()
:mix.stylus('resources/stylus/app.styl', 'public/css', { use: [ require('rupture')() ] });
PostCSS
PostCSS is a powerful tool for converting CSS, and it is included in Laravel Mix. By default, Mix automatically appends all necessary CSS3 third-party prefixes using the popular Autoprefixer plugin. However, you are free to add any additional plugins you want in your app. First install the required plug-ins through NPM, and then reference the
webpack.mix.js
file:mix.sass('resources/sass/app.scss', 'public/css') .options({ postCss: [ require('postcss-css-variables')() ] });
Native CSS
If you want to combine several native CSS stylesheets into a single file, you can use the
styles
method.mix.styles([ 'public/css/vendor/normalize.css', 'public/css/vendor/videojs.css'], 'public/css/all.css' );
URL processing
Because it is built on Webpack, it is important to understand several Webpack concepts . For CSS compilation, Webpack will rewrite and optimize any
url()
calls with stylesheets. Although it may sound strange at first, it is indeed a powerful feature. Imagine we want to compile Sass containing relative URLs to images:.example { background: url('../images/example.png'); }
{note} Any absolute path given
url()
will be excluded from URL rewriting . For exampleurl('/images/thing.png')
orurl('http://example.com/images/thing.png')
will not be modified.By default, Laravel Mix and Webpack will find
example.png
, copy it to thepublic/images
folder, and then override the generatedurl()
in the stylesheet. Once this is done, the compiled CSS will look like:.example { background: url(/images/example.png?d41d8cd98f00b204e9800998ecf8427e); }
While this feature may be useful, the existing folder structure may already be configured as you expect. In this case, you can disable
url()
rewriting:mix.sass('resources/app/app.scss', 'public/css') .options({ processCssUrls: false });
Add this configuration to the
webpack.mix.js
file and Mix will no longer Match anyurl()
or copy the resource to the public directory. In other words, the compiled CSS looks the same as what you originally entered:.example { background: url("../images/thing.png"); }
##Source mapAlthough source mapping is disabled by default, it can be activated by calling themix.sourceMaps()
method in the
webpack.mix.jsfile. Although it increases the cost of compilation/execution, it can provide additional debugging information to browser development tools when compiling resources.
mix.js('resources/js/app.js', 'public/js') .sourceMaps();
Working with JavaScript
Mix provides several features that facilitate working with JavaScript files, such as compiling ECMAScript 2015, module packaging, minimizing and merging native JavaScript files. Even better, all of this works great with no configuration required.
mix.js('resources/js/app.js', 'public/js');
With just this line of code, you can support:
- ES2015 syntax
- Module
- Compile
.vue
document. - Minimize code for production environments.
Vendor extraction
Bind the application's own JavaScript and third-party libraries in There is a potential disadvantage: it makes long-term caching difficult. For example, a separate update to the application code will force the browser to re-download all third-party libraries, even if the third-party libraries have not changed.
If you plan to frequently update the JavaScript in your application, you should consider extracting the third-party library into its own file. This way, changes to the application code will not affect the
vendor.js
file cache. Mix'sextract
method provides convenience for this: Themix.js('resources/js/app.js', 'public/js') .extract(['vue'])
extract
method accepts all libraries you want to extract tovendor.js
or Array of modules as parameter. Using the code snippet from the example above, Mix will generate the following file:public/js/manifest.js
: Webpack runtime manifestpublic/js/vendor.js
: Third-party library codepublic/js/app.js
: Application Code
To avoid JavaScript errors, make sure these files are loaded in the appropriate 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-ins required for React support. To achieve this, just replace
mix.js()
withmix.react()
:mix.react('resources/js/app.jsx', 'public/js');
Mix will download in the background and include the applicable
babel-preset-react
Babel plugin.Vanilla JS
is similar to integrating style sheets using
mix.styles()
, You can also consolidate and minify any number of JavaScript files using thescripts()
method:mix.scripts([ 'public/js/admin.js', 'public/js/dashboard.js'], 'public/js/all.js' );
This option is especially useful for legacy code that does not require JavaScript to be compiled using Webpack.
{tip}
mix.babel()
is a small variant ofmix.scripts()
. Its method signature is exactly the same asscripts
; but the integrated files will be compiled by Babel, which converts the ES2015 code into vanilla JavaScript that the browser understands.Custom Webpack Configuration
Lavarel Mix references a pre-configured
webpack.config.js
file behind the scenes to speed up startup and operation. Sometimes, you may need to edit this file manually. You may have a special loader or plugin you need to reference, or you may prefer to use Stylus instead of Sass. In this case, you have two options:Merge custom configuration
Mix provides the
webpackConfig
method to merge any short Webpack Configure to overwrite existing configuration. This is a very attractive option because it doesn't require you to copy and maintain your own copy ofwebpack.config.js
. ThewebpackConfig
method accepts an object as a parameter, which contains any Webpack specific configuration you want to apply,mix.webpackConfig({ resolve: { modules: [ path.resolve(__dirname, 'vendor/laravel/spark/resources/assets/js') ] } } );
custom configuration file
If you want to fully customize the Webpack configuration, copy the
node_modules/laravel-mix/setup/webpack.config.js
file to the root directory of your project. Then point all--config
references in thepackage.json
file to the newly copied configuration file. If you choose to customize the configuration in this way, any subsequent updates to Mixwebpack.config.js
must be manually merged into your custom configuration file.Copy files & directories
copy
method can be used to copy files and directories to a new location. This method is useful when special resources in thenode_modules
directory need to be relocated to thepublic
folder.mix.copy('node_modules/foo/bar.css', 'public/css/bar.css');
When copying a folder, the
copy
method will flatten the directory structure. If you want to maintain the original structure of the directory, you need to use thecopyDirectory
method:mix.copyDirectory('resources/img', 'public/img');
##Version Management/Cache DestructionMany developers suffix their compiled resources with a timestamp or unique token, forcing the browser to load the new resource to replace the old copy of the code. Mix can handle them for you using theversion
method. The .
version
method automatically appends a unique hash value to all compiled file names, allowing for more convenient cache destruction:
mix.js('resources/js/app.js', 'public/js') .version();
In generating versioning After the file, you won't know the exact file name. Therefore, you need to use Laravel's globalmix
function in views to load the corresponding hash resource.
mixThe function automatically determines the current file name of the hash file:
<script src="{{ mix('/js/app.js') }}"></script>
Usually there is no need for versioned files during the development phase, you can only runnpm run production
Perform versioning:
mix.js('resources/js/app.js', 'public/js'); if (mix.inProduction()) { mix.version(); }
Browsersync reload
BrowserSync can automatically detect file changes and inject changes into the browser without manual refresh. You can call the
mix.browserSync()
method to turn on this support:mix.browserSync('my-domain.test'); // 或... // https://browsersync.io/docs/options mix.browserSync({ proxy: 'my-domain.test' });
You can pass a string (proxy) or object Y (BrowserSync settings) to this method. Then use the
##Environment variables can be added by addingnpm run watch
command to start the Webpack development server. Edit the script or PHP file again and you will see the browser refresh immediately in response to your modifications.MIX_ in the
.env
filePrefix, inject environment variables into Mix:
MIX_SENTRY_DSN_PUBLIC=http://example.com
Once this variable is defined in the.env
file, it can be accessed with the help of the
process.envobject it. If this value changes when running the
watchtask, you need to restart the task:
process.env.MIX_SENTRY_DSN_PUBLIC
##NotificationIf available, Mix will automatically display operating system notifications for each bind. This will give you real-time feedback on whether the compilation was successful. However, there may be situations where you want to disable notifications. An example is triggering Mix on a production server. Notifications can be disabled with the help of the
disableNotificationsmethod.
LearnKu.com
This article was first published on themix.disableNotifications();