innocenzi/laravel-encore

This package is abandoned and no longer maintained. The author suggests using the innocenzi/laravel-vite package instead.

Integrate Webpack Encore in Laravel.

v0.5.0 2022-02-17 11:35 UTC

This package is auto-updated.

Last update: 2023-02-27 09:58:37 UTC


README

Laravel Encore

Latest version on Packagist   Total Downloads   Build

This package helps integrating Webpack Encore with Laravel.

Note: while this package should work, I'm not planning on fixing potential issues or updating it, since I'm no longer using it. If you want a better development environment, consider Laravel Vite using the new Vite integration from the Laravel team.

Installation

You can install the package via composer:

composer require innocenzi/laravel-encore

Installing Encore

Remove laravel-mix and add @symfony/webpack-encore.

yarn remove laravel-mix
yarn add @symfony/webpack-encore --dev

Remove your webpack.mix.js and create a webpack.config.js. Here is an example:

const Encore = require('@symfony/webpack-encore');

if (!Encore.isRuntimeEnvironmentConfigured()) {
  Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
  .setOutputPath('public/build/')
  .setPublicPath('/build')
  .addEntry('app', './resources/js/app.js')
  .splitEntryChunks()
  .enableSingleRuntimeChunk()
  .enablePostCssLoader()
  .cleanupOutputBeforeBuild()
  .enableSourceMaps(!Encore.isProduction())
  .enableVersioning(Encore.isProduction());

module.exports = Encore.getWebpackConfig();

Make sure resources/js/app.js exists. Ideally, it should import your CSS as well, but if you don't want to, you can add addStyleEntry to your Encore configuration.

// resources/js/app.js
import '../css/app.css';

Make sure you add public/build/ (or whatever output path you set) to your .gitignore.

Last, but not least, you should replace the scripts in your package.json with the following:

// package.json
{
  "scripts": {
    "dev-server": "encore dev-server",
    "dev": "encore dev",
    "watch": "encore dev --watch",
    "build": "encore production --progress"
  }
}

Usage

In your blade components, use the @styles and @scripts directives to include the assets generated by Encore.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel</title>
    <!-- Include assets -->
    @styles
    @scripts
  </head>
  <body>
    Hello.
  </body>
</html>

By default, it will look for the app entries, but you can change them by passing an entry name in each directive.

@styles('app')
@scripts('admin')

If you used static assets, you can use Encore::asset('build/path/to/your/asset.png') to include it. Under the hood, it's just a mapping to the manifest.json.

License

The MIT License (MIT). Please see License File for more information.