Not able to access right node_modules path on webpack-rails - ruby-on-rails

I am trying for the first time to work with angularjs with rails as the back end. I am using webpack-rails gem for the webpack configuration for managing css and other style sheets.
First I made a sample angular + rails app to display a simple text "Hello world". By default the font was in times new roman. Then I added bootstrap to the package.json file as follows.
package.json
{
"name": "shine",
"version": "0.0.1",
"license": "MIT",
"dependencies": {
"stats-webpack-plugin": "^0.4.3",
"webpack": "^1.14.0",
"webpack-dev-server": "^1.16.2",
"css-loader": "^0.23.1",
"file-loader": "^0.9.0",
"style-loader": "^0.13.1",
"url-loader": "^0.5.7",
"bootstrap": "3.3.7"
}
}
Then I ran npm install which generated a folder named node_modules
with all the packages mentioned in the package.json in Project/node_modules path.
And webpack configuration to access access these package files is given in the
webpack.config.js
'use strict';
var path = require('path');
var webpack = require('webpack');
var StatsPlugin = require('stats-webpack-plugin');
// must match config.webpack.dev_server.port
var devServerPort = 3808;
// set NODE_ENV=production on the environment to add asset fingerprints
var production = process.env.NODE_ENV === 'production';
var config = {
entry: {
// Sources are expected to live in $app_root/webpack
'application': './webpack/application.js'
},
output: {
// Build assets directly in to public/webpack/, let webpack know
// that all webpacked assets start with webpack/
// must match config.webpack.output_dir
path: path.join(__dirname, '..', 'public', 'webpack'),
publicPath: '/webpack/',
filename: production ? '[name]-[chunkhash].js' : '[name].js'
},
resolve: {
root: path.join(__dirname, '..', 'webpack')
},
plugins: [
// must match config.webpack.manifest_filename
new StatsPlugin('manifest.json', {
// We only need assetsByChunkName
chunkModules: false,
source: false,
chunks: false,
modules: false,
assets: true
})]
};
if (production) {
config.plugins.push(
new webpack.NoErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({
compressor: { warnings: false },
sourceMap: false
}),
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify('production') }
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin()
);
} else {
config.devServer = {
port: devServerPort,
headers: { 'Access-Control-Allow-Origin': '*' }
};
config.output.publicPath = '//localhost:' + devServerPort + '/webpack/';
// Source maps
config.devtool = 'cheap-module-eval-source-map';
}
module.exports = config;
And in my webpack/application.js I am calling that bootstrap package as follows.
require("bootstrap/dist/css/bootstrap.css");
console.log("Hello world!");
Now when I restart the server and reload the page I don't see any change in the font instead in the console I am getting.
Uncaught Error: Cannot find module "bootstrap/dist/css/bootstrap.css"
at webpackMissingModule
What am I doing wrong here ?

perhaps...
require('boostrap');
if that doesn't work, check to see if the file bootstrap/dist/css/bootstrap.css exists

Related

webpackMissingModule application.js on rails with angular app

I am following the steps like given by the author.
Following is the
package.json
{
"name": "shine",
"version": "0.0.1",
"license": "MIT",
"dependencies": {
"stats-webpack-plugin": "^0.4.3",
"webpack": "^1.14.0",
"webpack-dev-server": "^1.16.2",
"css-loader": "^0.23.1",
"file-loader": "^0.9.0",
"style-loader": "^0.13.1",
"url-loader": "^0.5.7",
"bootstrap": "3.3.7"
}
}
I am trying to change the default font to a different font by requiring the bootstrap.
My application.js looks like this
require("bootstrap/dist/css/bootstrap.css");
console.log("Hello world!");
And then I restarted the server. I see the text content are in same font-family as before nothing has changed when it should be actually a different font. And the console is giving the error as follows.
console
Uncaught Error: Cannot find module "bootstrap/dist/css/bootstrap.css"
at webpackMissingModule
webpack.config.js
// Example webpack configuration with asset fingerprinting in production.
'use strict';
var path = require('path');
var webpack = require('webpack');
var StatsPlugin = require('stats-webpack-plugin');
// must match config.webpack.dev_server.port
var devServerPort = 3808;
// set NODE_ENV=production on the environment to add asset fingerprints
var production = process.env.NODE_ENV === 'production';
var config = {
entry: {
// Sources are expected to live in $app_root/webpack
'application': './webpack/application.js'
},
output: {
// Build assets directly in to public/webpack/, let webpack know
// that all webpacked assets start with webpack/
// must match config.webpack.output_dir
path: path.join(__dirname, '..', 'public', 'webpack'),
publicPath: '/webpack/',
filename: production ? '[name]-[chunkhash].js' : '[name].js'
},
resolve: {
root: path.join(__dirname, '..', 'webpack')
},
plugins: [
// must match config.webpack.manifest_filename
new StatsPlugin('manifest.json', {
// We only need assetsByChunkName
chunkModules: false,
source: false,
chunks: false,
modules: false,
assets: true
})]
};
if (production) {
config.plugins.push(
new webpack.NoErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({
compressor: { warnings: false },
sourceMap: false
}),
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify('production') }
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin()
);
} else {
config.devServer = {
port: devServerPort,
headers: { 'Access-Control-Allow-Origin': '*' }
};
config.output.publicPath = '//localhost:' + devServerPort + '/webpack/';
// Source maps
config.devtool = 'cheap-module-eval-source-map';
}
module.exports = config;
I am not able to figure out if this is npm installing issue or something else. How can I fix this.
It seems your using older version of webpack, which I infer after seeing the resolve.root property. From webpack 1 docs
The directory (absolute path) that contains your modules. May also be an array of directories. This setting should be used to add individual directories to the search path.
So when your bootstrap.css files is being resolved instead of searching node_modules, it searches in your
resolve: { root: path.join(__dirname, '..', 'webpack')}

React on Rails with server side rendering

I created a site using React on Rails. It works perfectly fine, but I have not noticed that server side rendering is turned off, and I need it for SEO so I decided to turn it on. The thing is that now I get an error like this:
ERROR in SERVER PRERENDERING
Encountered error: "ReferenceError: window is not defined"
My webpack.config.js looks like this:
/* eslint comma-dangle: ["error",
{"functions": "never", "arrays": "only-multiline", "objects":
"only-multiline"} ] */
const webpack = require('webpack');
const path = require('path');
const devBuild = process.env.NODE_ENV !== 'production';
const nodeEnv = devBuild ? 'development' : 'production';
const bundles = [
'./app/bundles/Home/startup/registration'
]
const config = {
entry: [
'es5-shim/es5-shim',
'es5-shim/es5-sham',
'babel-polyfill',
...bundles
],
output: {
filename: 'webpack-bundle.js',
path: '../app/assets/webpack',
},
resolve: {
extensions: ['', '.js', '.jsx'],
alias: {
react: path.resolve('./node_modules/react'),
'react-dom': path.resolve('./node_modules/react-dom'),
},
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(nodeEnv),
},
}),
],
module: {
loaders: [
{
test: require.resolve('react'),
loader: 'imports?shim=es5-shim/es5-shim&sham=es5-shim/es5-sham',
},
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
},
],
},
};
module.exports = config;
if (devBuild) {
console.log('Webpack dev build for Rails'); // eslint-disable-line no-console
module.exports.devtool = 'eval-source-map';
} else {
config.plugins.push(
new webpack.optimize.DedupePlugin()
);
console.log('Webpack production build for Rails'); // eslint-disable-line no-console
}
What should I do to fix it? I read through one of the realted issues on react_on_rails github but I still do not know.

Accessing webpack assets from rails app

I'm using webpack with React on Rails and have some react components that need to reference images.
The problem I'm having is trying to get Rails to access the images. Rails has its images served from its usual app/assets/images directory which is accessed via the url /assets
If however I have a react component and an image in an image directory:
component.js
images/image.jpg
+--component.js
+--images/image.jpg
If I try to reference the image by its relative path within component.js eg When I load the page in rails the page tries to access the url http://localhost:3000/home/images/image.jpg and not the url that rails expects the assets to be http://localhost:3000/assets/images/image.jpg
Does anyone know how to correct this?
This is my webpack.config
const webpack = require('webpack')
const path = require('path')
const devBuild = process.env.NODE_ENV !== 'production'
const nodeEnv = devBuild ? 'development' : 'production'
const config = {
entry: [
'whatwg-fetch',
'es5-shim/es5-shim',
'es5-shim/es5-sham',
'babel-polyfill',
'./app/bundles/index.js'
],
output: {
filename: 'webpack-bundle.js',
path: '../app/assets/webpack'
},
resolve: {
extensions: ['', '.js', '.jsx'],
alias: {
react: path.resolve('./node_modules/react'),
'react-dom': path.resolve('./node_modules/react-dom')
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(nodeEnv)
}
})
],
module: {
loaders: [
{
test: require.resolve('react'),
loader: 'imports?shim=es5-shim/es5-shim&sham=es5-shim/es5-sham'
},
{
test: /\.(jpe?g|png|gif|svg|ico)$/, loader: 'file-loader'
},
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
}
}
module.exports = config
if (devBuild) {
console.log('Webpack dev build for Rails') // eslint-disable-line no-console
module.exports.devtool = 'eval-source-map'
} else {
config.plugins.push(
new webpack.optimize.DedupePlugin()
)
console.log('Webpack production build for Rails') // eslint-disable-line no-console
}

use jquery-ui with webpack having a particular file structure

I would like you to help/suggest the best way to use datepicker from jquery-ui having the following file structure:
-single_pages
-admin
-admin.js
-webpack.config.js
-common
-DatesFilter
-DatesFilter.js
-node_modules
-package.json
I already installed jquery-ui
My webpack.config.js file is:
var path = require('path');
var webpack = require("webpack");
module.exports = {
resolve: {
alias: {
'jquery': require.resolve('jquery'),
},
root: [
path.resolve(__dirname, './../admin'),
path.resolve(__dirname, './../common')
],
extensions: ['', '.js'],
fallback: path.resolve(__dirname, './../node_modules')
},
resolveLoader: {
fallback: path.resolve(__dirname, './../node_modules')
},
entry: './index.js',
output: {
filename: 'bundle.js',
publicPath: "/"
},
externals: {
// require("jquery") is external and available
// on the global var jQuery
"jquery": "jQuery"
},
plugins: [
new webpack.ProvidePlugin({
"$":"jquery",
"jQuery":"jquery",
"window.jQuery":"jquery"
})
],
module: {
loaders: [
{
test: /\.js$/,
include: [
path.resolve(__dirname, './')
],
loader: "babel-loader"
},
{
test: /\.js$/,
include: path.resolve(__dirname, './../common'),
babelrc: false,
loader: require.resolve('babel-loader'),
query: { // load the same presets as in the .babelrc file, but in a way that resolves in the parent directory
presets: [require.resolve('babel-preset-es2015'), require.resolve('babel-preset-react'),
require.resolve('babel-preset-stage-0')]
}
}
]
}
};
I'm using React.js.
I import DatesFilter.js inside admin.js. I get to see the component. The problem comes when I want to use the datepicker.
DatesFilter.js uses datepicker from jquery-ui
I'm using: import { datepicker } from 'jquery-ui' inside DatesFilter.js but it keeps saying TypeError: $(...).datepicker is not a function
What can I do?
Thank you
Try importing just the module, see this link jquery-ui-and-webpack-how-to-manage-it-into-module
in your case you would import "jquery-ui/ui/widgets/datepicker"

Rails + React + Webpack loading an image

I'm using rails + webpack to compile a bundle.js file into the rails asset pipeline. I placed an image inside /app/assets/images called "main.png". How can I access this image inside a React component that's being bundled?
I'm using shakacode's react on rails gem. https://github.com/shakacode/react_on_rails
I then tried using webpack to process the image which it did successfully and placed the image next to the bundle.js file. I still get a 404 on the image.
I know I'm close, just have the publicPath wrong for the rails asset. This current setup gives a localhost:3000/webpack/main.png which isn't working with rails.
This is my webpack file:
const webpack = require('webpack');
const path = require('path');
const devBuild = process.env.NODE_ENV !== 'production';
const nodeEnv = devBuild ? 'development' : 'production';
config = {
entry: [
'es5-shim/es5-shim',
'es5-shim/es5-sham',
'babel-polyfill',
'./app/Register.js',
],
output: {
filename: 'webpack-bundle.js',
path: '../app/assets/webpack',
publicPath: '/webpack/'
},
resolve: {
extensions: ['', '.js', '.jsx'],
alias: {
react: path.resolve('./node_modules/react'),
'react-dom': path.resolve('./node_modules/react-dom'),
},
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(nodeEnv),
},
}),
],
module: {
loaders: [
{
test: require.resolve('react'),
loader: 'imports?shim=es5-shim/es5-shim&sham=es5-shim/es5-sham',
},
{
test: /\.jsx?$/, loader: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.(png|svg)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&interlaced=false'
]
}
],
},
};
module.exports = config;
if (devBuild) {
console.log('Webpack dev build for Rails'); // eslint-disable-line no-console
module.exports.devtool = 'eval-source-map';
} else {
config.plugins.push(
new webpack.optimize.DedupePlugin()
);
console.log('Webpack production build for Rails'); // eslint-disable-line no-console
}
After defining a loader properly, you can load your image with a require function, for example! For example, add near your imports:
const myImg = require('./assets/methods.png');
Then, in your component's render method:
<img src={myImg} />
That should work...

Resources