How to add the theme javascript files with webpack?

by aniya.jaskolski , in category: Javascript , a year ago

How to add the theme javascript files with webpack?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , a year ago

@aniya.jaskolski 

To add theme javascript files with webpack, you can follow these steps:

  1. Make sure you have webpack installed in your project. If not, you can install it using npm or yarn:
1
npm install webpack --save-dev


or

1
yarn add webpack --dev


  1. Create a webpack configuration file (webpack.config.js) in the root of your project directory.
  2. In the webpack configuration file, you can define an entry point for your theme javascript file. For example, if your theme javascript file is located in a folder called "js" and named "theme.js", you can set the entry point like this:
1
2
3
4
5
6
7
8
9
const path = require('path');

module.exports = {
  entry: './js/theme.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'theme.bundle.js'
  }
};


  1. Install any necessary loaders or plugins for handling javascript files. For example, you may need to install babel-loader to transpile ES6 code to ES5:
1
npm install babel-loader @babel/core @babel/preset-env --save-dev


  1. Update your webpack configuration file to use the babel-loader for javascript files:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
module.exports = {
  entry: './js/theme.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'theme.bundle.js'
  },
  module: {
    rules: [
      {
        test: /.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  }
};


  1. Once you have set up your webpack configuration file and installed any necessary loaders or plugins, you can run webpack to bundle your theme javascript files:
1
npx webpack


This will generate a bundled javascript file (e.g., theme.bundle.js) in the specified output directory (e.g., dist). You can link this bundled javascript file in your HTML file to use it in your theme.

Related Threads:

How to defer javascript files in theme.liquid in shopify?
How to prepend outputs files with webpack?
How to use the .env files config from webpack to vite?
How to replace a string in javascript using webpack?
How to repair npm run build in webpack?Javascript
How to require .css, .js files inside html file in webpack?