<p>So what you want to compile a second JS file that's output seperately from the main JS file? In this case, you'll have to adjust the webpack config. The <a href="https://github.com/craftcms/starter-blog/blob/main/webpack.config.js" rel="nofollow noreferrer">webpack.config.js</a> in the starter project doesn't specify an explicit entry point, which means the default of <code>src/index.js</code> is used. You can overwrite this by specyfing one or multiple <a href="https://webpack.js.org/concepts/entry-points/" rel="nofollow noreferrer">entry points as per the documentation</a>. Include something like this in your <code>webpack.config.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>config = {
    // ...
    entry: {
        main: 'src/index.js',
        myCustomComponent: `src/myCustomComponent.js`,
    }
    // ...
}
</code></pre>
<p>Then create the specified file <code>src/myCustomComponent.js</code> and put your page-specific JavaScript in there.</p>
<p>This should work without further adjustments since the <a href="https://github.com/craftcms/starter-blog/blob/main/webpack.config.js#L38-L43" rel="nofollow noreferrer">default output config</a> in the starter project already supports multiple entry points by using placeholders for the target filename:</p>
<pre class="lang-js prettyprint-override"><code>filename: devMode ? &quot;[name].js&quot; : &quot;[name].[fullhash].js&quot;,
</code></pre>
<p>With the additional entry points, the webpack build step should result in two output files:</p>
<ul>
<li><code>/web/assets/dist/index.js</code></li>
<li><code>/web/assets/dist/myCustomComponent.js</code></li>
</ul>
<p>Both of those files will be compiled using the same rules specified by the Webpack config. In production mode, the output filenames will include the content hash (e.g. <code>index.abcd1234.js</code>, <code>myCustomComponent.efgh5678.js</code>). Those filenames will be written to the manifest by the Webpack manifest plugin, so now you can simply use the <code>rev</code> function to get the current asset path for your custom asset:</p>
<pre class="lang-twig prettyprint-override"><code>{% js rev('myCustomComponent.js') at head with { defer: true } %}
</code></pre>
<hr />
<p>As a sidenote, I would recommend not using a starter template if you're just starting out. Unless you understand everything it's doing and the benefits it brings, it will just introduce complexity into your project that you're unable to debug or work productively with. Besides, the starter blog is, in my opinion, way more complicated than it needs to be. The webpack build in particular is really overkill, I've built much more complicated projects with a much simpler Webpack config. My recommendation would be to start with the <a href="https://github.com/craftcms/craft" rel="nofollow noreferrer">blank starter project</a> and use the starter blog as inspiration to draw from if you get stuck.</p>

CC BY-SA 4.0
2022-06-04T11:50:28.520Z
Thank you sir. This worked. But it compiles a very long js file for a simple console.log on my separate js file. Should I go with approach or not? What is the best practice of using a page specific js file Sir?
user
CC BY-SA 4.0
2022-06-06T10:17:13.877Z
@user Yes, Webpack does tend to create larger files. It has some overhead of its own, and the Webpack config in the starter project also includes [Babel](https://babeljs.io/), which will transpile and/or add polyfills to your code as required. Though make sure you check the compiled output for production, not dev mode, as the latter is much more verbose. If you don't want all of that for your page-specific JavaScript, you can also use the CopyWebpackPlugin to copy the JS file over without modifications.
MoritzLost
CC BY-SA 4.0
2022-06-06T10:17:31.903Z
There isn't a best practice, it depends on what you need to Webpack build for. Again, if you don't need Webpack or don't see the benefit of it, start with something simpler and only add additional libraries and tools as you encounter problems where they will actually make your work easier.
MoritzLost
CC BY-SA 4.0
2022-06-04T10:58:28.227Z
2022-06-04T10:58:28.227Z
MoritzLost
<p>I Suggest to use Webpack with Laravel mix to fast approach.<br>
Here is my setup. if need full file let me know.</p>
<pre><code>const mix = require('laravel-mix');
mix.version();

mix.setPublicPath('web/assets');
mix.js('src/js/app.js', 'js');

mix.browserSync({
proxy: process.env.PRIMARY_SITE_URL,
files: [
    'templates/**/*',
    'web/assets/**/*',
],
browser: process.env.LOCAL_BROWSER,
injectChanges: true
});
</code></pre>
<p>And instead of rev use mix.</p>

CC BY-SA 4.0
2022-06-10T14:45:00.713Z
give me full starter template. I want to try this. thank you.
user
CC BY-SA 4.0
2022-06-10T06:39:20.560Z
2022-06-10T06:39:20.560Z
Taher Kathiriya
<p>Here is full Template</p>
<pre><code>const mix = require('laravel-mix');

require('laravel-mix-tailwind');
require('laravel-mix-copy-watched');

// require('laravel-mix-purgecss');
// const purgeExclude = require('./purge.mix.js');

// const purgeContent = [
//   &quot;templates/**/*.php&quot;,
//   &quot;templates/**/*.twig&quot;,
//   &quot;templates/**/*.html&quot;,
//   &quot;templates/**/*.json&quot;,
//   &quot;templates/**/*.js&quot;,
//   &quot;templates/**/*.rss&quot;,
//   &quot;src/js/**/*.js&quot;,
//   &quot;web/assets/icons/**/*.svg&quot;,
// ];

/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel applications. By default, we are compiling the CSS
| file for the application as well as bundling up all the JS files.
|
*/

mix.version();
// mix.sourceMaps();
mix.disableSuccessNotifications();

mix.options({
    autoprefixer: {
        remove: false
    }
});

mix.autoload({
    jquery: ['$', 'window.$', 'window.jQuery']
});

mix.setPublicPath('web/assets');

mix.js('src/js/app.js', 'js');

/*mix.sass( 'src/scss/all.scss', 'css' ).purgeCss({
  enabled: (process.env.PURGE_CSS == &quot;true&quot; ? true : false),
  content: purgeContent,
  safelist: { standard: purgeExclude.whitelist }
});*/

mix.sass('src/scss/all.scss', 'css');

// mix.copyWatched( 'src/images', 'web/assets/images' );
mix.tailwind();

mix.browserSync({
    proxy: process.env.PRIMARY_SITE_URL,
    files: [
        'templates/**/*',
        'web/assets/**/*',
    ],
    browser: process.env.LOCAL_BROWSER,
    injectChanges: true
});
</code></pre>

CC BY-SA 4.0
2022-06-14T06:39:05.273Z
2022-06-14T06:39:05.273Z
Taher Kathiriya
<p>I have a similar question <a href="https://craftcms.stackexchange.com/questions/39465/how-to-use-page-specific-javascript-using-the-starter-blog-template-using-asset">here</a>.</p>
<p>But I was NOT able to ask the right question.</p>
<p>I'm practicing with <a href="https://github.com/craftcms/starter-blog" rel="nofollow noreferrer">starter-blog template</a>.</p>
<p>How do I use page specific javascript using the <code>asset rev</code> plugin and <code>webpack</code>?
I don't want to manually add the js file inside the <code>assets</code> folder.</p>
<p>I want to write it inside the <code>src</code> folder and let webpack compile it to the <code>assets</code> folder.</p>
<p>Please help. Thank you.</p>

<javascript>
How to use page specific javascript using asset rev plugin and webpack?
# How to use page specific javascript using asset rev plugin and webpack?

(Asked by: username_0 on 2022-06-04)

I have a similar question [here](https://craftcms.stackexchange.com/questions/39465/how-to-use-page-specific-javascript-using-the-starter-blog-template-using-asset).

But I was NOT able to ask the right question.

I'm practicing with [starter-blog template](https://github.com/craftcms/starter-blog).

How do I use page specific javascript using the `asset rev` plugin and `webpack`?
I don't want to manually add the js file inside the `assets` folder.

I want to write it inside the `src` folder and let webpack compile it to the `assets` folder.

Please help. Thank you.

**Tags:** javascript


---

## 3 answers

### Answer by username_1 on 2022-06-04. Score: 3 | Accepted answer

So what you want to compile a second JS file that's output seperately from the main JS file? In this case, you'll have to adjust the webpack config. The webpack.config.js in the starter project doesn't specify an explicit entry point, which means the default of src/index.js is used. You can overwrite this by specyfing one or multiple entry points as per the documentation. Include something like this in your webpack.config.js:
config = {
    // ...
    entry: {
        main: 'src/index.js',
        myCustomComponent: `src/myCustomComponent.js`,
    }
    // ...
}

Then create the specified file src/myCustomComponent.js and put your page-specific JavaScript in there.
This should work without further adjustments since the default output config in the starter project already supports multiple entry points by using placeholders for the target filename:
filename: devMode ? "[name].js" : "[name].[fullhash].js",

With the additional entry points, the webpack build step should result in two output files:

/web/assets/dist/index.js
/web/assets/dist/myCustomComponent.js

Both of those files will be compiled using the same rules specified by the Webpack config. In production mode, the output filenames will include the content hash (e.g. index.abcd1234.js, myCustomComponent.efgh5678.js). Those filenames will be written to the manifest by the Webpack manifest plugin, so now you can simply use the rev function to get the current asset path for your custom asset:
{% js rev('myCustomComponent.js') at head with { defer: true } %}


As a sidenote, I would recommend not using a starter template if you're just starting out. Unless you understand everything it's doing and the benefits it brings, it will just introduce complexity into your project that you're unable to debug or work productively with. Besides, the starter blog is, in my opinion, way more complicated than it needs to be. The webpack build in particular is really overkill, I've built much more complicated projects with a much simpler Webpack config. My recommendation would be to start with the blank starter project and use the starter blog as inspiration to draw from if you get stuck.

> **Comments:**
> **username_0**: Thank you sir. This worked. But it compiles a very long js file for a simple console.log on my separate js file. Should I go with approach or not? What is the best practice of using a page specific js file Sir?  
> **username_1**: @username_0 Yes, Webpack does tend to create larger files. It has some overhead of its own, and the Webpack config in the starter project also includes [Babel](https://babeljs.io/), which will transpile and/or add polyfills to your code as required. Though make sure you check the compiled output for production, not dev mode, as the latter is much more verbose. If you don't want all of that for your page-specific JavaScript, you can also use the CopyWebpackPlugin to copy the JS file over without modifications.  
> **username_1**: There isn't a best practice, it depends on what you need to Webpack build for. Again, if you don't need Webpack or don't see the benefit of it, start with something simpler and only add additional libraries and tools as you encounter problems where they will actually make your work easier.  

---

### Answer by username_2 on 2022-06-10. Score: 1

I Suggest to use Webpack with Laravel mix to fast approach.
Here is my setup. if need full file let me know.
const mix = require('laravel-mix');
mix.version();

mix.setPublicPath('web/assets');
mix.js('src/js/app.js', 'js');

mix.browserSync({
proxy: process.env.PRIMARY_SITE_URL,
files: [
    'templates/**/*',
    'web/assets/**/*',
],
browser: process.env.LOCAL_BROWSER,
injectChanges: true
});

And instead of rev use mix.

> **Comments:**
> **username_0**: give me full starter template. I want to try this. thank you.  

---

### Answer by username_2 on 2022-06-14. Score: 1

Here is full Template
const mix = require('laravel-mix');

require('laravel-mix-tailwind');
require('laravel-mix-copy-watched');

// require('laravel-mix-purgecss');
// const purgeExclude = require('./purge.mix.js');

// const purgeContent = [
//   "templates/**/*.php",
//   "templates/**/*.twig",
//   "templates/**/*.html",
//   "templates/**/*.json",
//   "templates/**/*.js",
//   "templates/**/*.rss",
//   "src/js/**/*.js",
//   "web/assets/icons/**/*.svg",
// ];

/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel applications. By default, we are compiling the CSS
| file for the application as well as bundling up all the JS files.
|
*/

mix.version();
// mix.sourceMaps();
mix.disableSuccessNotifications();

mix.options({
    autoprefixer: {
        remove: false
    }
});

mix.autoload({
    jquery: ['$', 'window.$', 'window.jQuery']
});

mix.setPublicPath('web/assets');

mix.js('src/js/app.js', 'js');

/*mix.sass( 'src/scss/all.scss', 'css' ).purgeCss({
  enabled: (process.env.PURGE_CSS == "true" ? true : false),
  content: purgeContent,
  safelist: { standard: purgeExclude.whitelist }
});*/

mix.sass('src/scss/all.scss', 'css');

// mix.copyWatched( 'src/images', 'web/assets/images' );
mix.tailwind();

mix.browserSync({
    proxy: process.env.PRIMARY_SITE_URL,
    files: [
        'templates/**/*',
        'web/assets/**/*',
    ],
    browser: process.env.LOCAL_BROWSER,
    injectChanges: true
});


---

