Webpack with requirejs/AMD

18,428

I had the same question and I managed to achieve it. Below is the same webpack.config.js file.

const fs = require('fs');
const path = require('path');
const webpack = require('webpack');

let basePath = path.join(__dirname, '/');

let config = {
  // Entry, file to be bundled
  entry: {
    'main': basePath +  '/src/main.js',
  },
  devtool: 'source-map',
  output: {
    // Output directory
    path: basePath +  '/dist/',
    library: '[name]',
    // [hash:6] with add a SHA based on file changes if the env is build
    filename: env === EnvEnum.BUILD ? '[name]-[hash:6].min.js' : '[name].min.js',
    libraryTarget: 'amd',
    umdNamedDefine: true
  },
  module: {
    rules: [{
      test: /(\.js)$/,
      exclude: /(node_modules|bower_components)/,
      use: {
        // babel-loader to convert ES6 code to ES5 + amdCleaning requirejs code into simple JS code, taking care of modules to load as desired
        loader: 'babel-loader',
        options: {
          presets: ['es2015'],
          plugins: []
        }
      }
    }, { test: /jQuery/, loader: 'expose-loader?$' }, 
  { test: /application/, loader: 'expose-loader?application' },
  { test: /base64/, loader: 'exports-loader?Base64' }
    ]
  },
  resolve: {
    alias: {
        'jQuery': 'bower_components/jquery/dist/jquery.min',
        'application': 'main',
        'base64': 'vendor/base64'
    },
    modules: [
      // Files path which will be referenced while bundling
      'src/**/*.js',
      'src/bower_components',
      path.resolve('./src')
    ],
    extensions: ['.js'] // File types
  },
  plugins: [

  ]
};

module.exports = config;
Share:
18,428

Related videos on Youtube

goldensausage
Author by

goldensausage

Updated on June 25, 2022

Comments

  • goldensausage
    goldensausage about 2 years

    I'm working on a new module for an existing project that still uses requireJS for module loading. I'm trying to use new technologies for my new module like webpack (which allows me to use es6 loaders using es6 imports). It seems like webpack can't reconcile with requireJS syntax. It will say things like: "Module not found: Error: Can't resolve in ".

    Problem: Webpack won't bundle files with requireJS/AMD syntax in them.
    Question: Is there any way to make webpack play nice with requireJS?

    My final output must be in AMD format in order for the project to properly load it. Thanks.

    • Andres M
      Andres M about 7 years
      You could take a look at some of the babel loaders for webpack. I had similar issues, you can usually transpile between module systems using babel
    • goldensausage
      goldensausage about 7 years
      im already using babel loader in my webpack config
  • crmpicco
    crmpicco over 5 years
    Is it possible to do this with Webpack Encore?