To preface, I'm aware that I should probably avoid using Bower and instead use NPM to manage all my JavaScript dependencies. However, I'm working with some legacy code which uses Bower heavily, and until I can move everything over to NPM, I'd like to get a working version of my code base with Bower and Webpack.
That being said, I'm following the configuration setup for using Bower with Webpack from the official guide: https://webpack.github.io/docs/usage-with-bower.html
In particular, I've set up a Github repo where I was able to bower install jquery
and using the configuration from the official guide, I was able to require("jquery")
in my source code and have it work with Webpack. Given that this worked for jQuery, I assumed that it would work for other bower packages, including React.
However, after running bower install react
, I attempted to require("react")
in my source code but Webpack threw an error saying, Module not found: Error: Cannot resolve module 'react' in /Users/wmock/Desktop/using-bower-with-webpack/src
.
This is my Github repo: https://github.com/fay-jai/Using-Bower-Through-Webpack
I have 3 branches:
Question:
EDIT (4/12/2016):
DirectoryDescriptionFilePlugin can't deal with arrays of filenames, so you can't import React, and ReactDOM. You can use a plugin like Bower Webpack Plugin to solve the array problem, but it only imports the first file in the array, and ignores the rest, so React can be imported, but ReactDOM can't.
Aliasing the files by yourself will always work. The main drawback is that you'll need to alias every bower dependency manually.
resolve: {
alias: {
"jquery": bower_dir + "/jquery/dist/jquery.js",
"react": bower_dir + "/react/react.js",
"react-dom": bower_dir + "/react/react-dom.js" // added alias for react-dom
}
}
You can actually combine DirectoryDescriptionFilePlugin resolve, with manual resolve via aliasing. Normal modules, such as jQuery will be resolved in the official way, and multi file modules can be aliased:
resolve: {
modulesDirectories: ["node_modules", "bower_components"],
alias: {
"react": bower_dir + "/react/react.js",
"react-dom": bower_dir + "/react/react-dom.js"
}
},
plugins: [
new webpack.ResolverPlugin(
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin(".bower.json", ["main"])
)
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With