Elkin
Elkin

Reputation: 900

Is there some workaround to make requireJS point to webpack modules bundled with alias?

Below are the pseudo configuration files for explanation purposes:

webpack.config

...
entry: {
    'animals': 'index' 
}
...

index.js

import * as Wolfs from './path/to/dogs';
import * as Tigers from './path/to/cats';
export {
  Wolfs,
  Tigers
}

Configuration of RequireJS

require.config( {
    ...
    'paths': {
        'dogs-requireJS-moduleID' : './path/to/dogs',
        'cats-requireJS-moduleID' : './path/to/cats',
        'animals-webpack-bundle'  : 'path/to/animals/bundle'           
     },
    'map': {
        '*': {
            'dogs-requireJS-moduleID': 'animals-webpack-bundle',
            'cats-requireJS-moduleID': 'animals-webpack-bundle'
         }
   });

Dependent module

import * as JohnDogs from 'dogs-requireJS-moduleID'; //This now points to animals-webpack-bundle 
JohnDogs.doStuff();

In order for the Dependent module to work, the code would have to be rewritten to JohnDogs.Wolfs.doStuff() because Dogs were exported with alias Wolfs. My question is if there is some workaround to make the code work without having to rewrite it.

Hope to have explained my problem well. Thanks in advance.

Update

The above is only psudeo code for explanation purposes. In my real scenario, there are other projects with their own webpack.config that depend on this project that I am bundling but I can't access them. Also, these projects share the same RequireJS configuration to which I have access.

Upvotes: 0

Views: 96

Answers (1)

DoneDeal0
DoneDeal0

Reputation: 6267

You don't need requireJS to create aliases. You can do it in webpack like this (insert this snippet in your webpack.config.js file)

const path = require("path");

/// ... webpack config
resolve: {
      extensions: [".ts", ".tsx", ".js", "jsx", ".json"],
      alias: {
        components: path.resolve(__dirname, "src/components/"),
        models: path.resolve(__dirname, "src/models/"),
        pages: path.resolve(__dirname, "src/pages/"),
        src: path.resolve(__dirname, "src/"),
      },
    },

Please note that if you're using Typescript, you will also need to write the aliases in your tsconfig.json:

// ... compilerOptions
"paths": {
      "components/*": ["src/components/*"],
      "pages/*": ["src/pages/*"],
      "src/*": ["src/*"]
    },

Then, you can import a file like this:

import Slider from "components/form/slider"

Last but not least, an alias should point toward an entry point, like components or assets. Don't point them toward specific files like in your exemple, else you will end up with thousand of entries, it's just not scalable.

Upvotes: 1

Related Questions