I am getting started to migrate my angular app to webpack. I have a file structure as belows:
- app/
------ app.js
------ index.html
- lib/
----- angular.js
----- jquery.js
----- ...
- webpack.config.js
Due to restrictions, I cannot use npm to install libraries. All my library files are located in lib and other folders. My webpack config looks like below:
var webpack = require('webpack'),
path = require('path');
module.exports = {
context: __dirname,
entry: {
app: [ './app/app.js'],
vendors: ['angular']
},
output: {
path: __dirname + '/build',
filename: 'bundle.js'
},
resolve: {
alias: {
angular: __dirname + "/lib/angular"
}
},
debug: false,
devtool: 'source-map',
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
},
{
test: /\.css$/,
loader: "style-loader!css-loader"},
{
test: /\.png$/,
loader: "url-loader?limit=100000"},
{
test: /\.jpg$/,
loader: "file-loader"
},
{
test: /\.json/,
loader: 'json'
}
]
},
plugins: [
new webpack.ProvidePlugin({
angular: "angular"
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js', Infinity)
]
}
I get the error
angular.js?848f:80Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
app.js looks like below
angular.module("myApp", [])
.controller("myCtrl", function(){ ... });
Thanks for the help!
First, fix typo vendor instead of vendors in your entries. It should match name in CommonsChunkPlugin
entry: {
app: [ './app/app.js'],
vendor: ['angular']
},
Second, remove ProvidePlugin
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js', Infinity)
]
Now it should works.
But i don't know if it's correct way to load external libs with webpack, actually. (Webpack is super black box for me, gulp is much more predictable). So now it works, but without proper DI.
Related
I was trying to get react-toolbox to run.
Got the error 'Cannot find module precss' but this is the same code I picked up from the site. Am I missing out on something?
postcss.config.js
module.exports = {
plugins: [
require('precss'),
require('autoprefixer')
]
}
webpack.config.js
var HTMLWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry: __dirname + '/app/index.js',
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.css$/,
loaders: [
'style-loader',
'css-loader?importLoaders=1',
'postcss-loader'
]
}
]
},
output: {
filename: 'transformed.js',
path: __dirname+'/build'
},
plugins: [HTMLWebpackPluginConfig]
};
Any thoughts?
What does your package.json look like? Have you added precss as a dependency to your project? You always have to make sure that everything you import/use actually exists in the project.
You can check this by opening your package.json file and checking if it's in the list of dependencies. If it isn't try running:
npm install --save precss
This will install it in your project and you should be able to run the command again.
Does anyone see what I'm doing wrong here in my webpack.config.js file? The browser gives me an error saying "unexpected token 'import' " which means it is not recognizing ES6 syntax. Am I doing something wrong with the loaders? I've installed and reinstalled dependencies multiple times, so I don't think that's where the issue lies.
webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./public/index.jsx'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
resolve: {
root: __dirname,
alias: {
App: 'public/components/App.jsx',
Home: 'public/components/Home.jsx',
Footer: 'public/components/Footer.jsx',
Inventory: 'public/components/Inventory.jsx',
Login: 'public/components/nav/Login.jsx',
Navbar: 'public/components/nav/Navbar.jsx',
ProductSearch: 'public/components/Product-Search.jsx',
SingleProduct: 'public/components/Single-Product.jsx',
Product: 'public/components/Product.jsx',
Signup: 'public/components/Signup.jsx',
LandingNavbar: 'public/components/nav/LandingNavbar.jsx',
ProductSearch: 'public/components/ProductSearch.jsx',
Examples: 'public/components/Examples.jsx',
Pricing: 'public/components/Pricing.jsx',
Profile: 'public/components/Profile.jsx',
Checkout: 'public/components/Checkout.jsx',
Receipt: 'public/components/Receipt.jsx',
RequireAuth: 'public/components/auth/require_auth.jsx',
Signout: 'public/components/Signout.jsx',
Tour: 'public/components/tour/Tour.jsx',
BusinessTypes: 'public/components/tour/BusinessTypes.jsx',
Customers: 'public/components/tour/Customers.jsx',
Features: 'public/components/tour/Features.jsx',
GettingStarted: 'public/components/tour/GettingStarted.jsx',
MultiStore: 'public/components/tour/MultiStore.jsx',
Support: 'public/components/tour/Support.jsx',
Actions: 'public/actions/index.js'
},
extensions: ['', '.js', '.jsx']
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [{
test: /\.jsx$/,
loaders: ['react-hot','babel-loader', 'babel?presets[]=es2015,presets[]=stage-0,presets[]=react'],
include: path.join(__dirname, 'public')
}]
}
};
You have the babel loader twice. Just remove 'babel-loader' from your array of loaders. This is because "babel?..." is calling the loader already.
Your package.json must have babel-loader in it. So make sure you run:
npm install babel-loader babel-core babel-preset-es2015 babel-preset-react babel-preset-stage-0 --save-dev
Then this in your webpack config file:
module: {
loaders: [{
test: /\.jsx$/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'stage-0', 'react']
},
include: path.join(__dirname, 'public')
}]
}
If that works, then try adding 'react-hot' to your list of loaders.
What file gives you this error? public/actions/index.js? You are not passing your .js files to babel.
And you are calling babel-loader twice. First as "babel-loader" without any preset and second as "babel" with presets.
Correct loaders would be:
loaders: [{
test: /\.jsx?$/,
loaders: ['react-hot', 'babel?presets[]=es2015,presets[]=stage-0,presets[]=react'],
include: path.join(__dirname, 'public')
}]
Note changed test regexp. Now it covers .js and .jsx files. And I suggest moving presets into .babelrc file
I use webpack and react in this project, and I want to import react-paginator in my project, but I get an error when I bundle front-end code.
I guess webpack did not parse the jsx code under node_modules folder, but I have no ideas how to solve......
error:
ERROR in ./~/react-paginator/index.js
Module parse failed: /home/kang/Desktop/doing/match-platform/node_modules/react-paginator/index.js Line 109: Unexpected token <
You may need an appropriate loader to handle this file type.
webpack config:
var webpack = require('webpack');
module.exports = {
entry: {
root: './src/front_end/scripts/root_container.js',
},
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets:['es2015', 'react']
}
}, {
test: /\.json$/,
loader: 'json'
}]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
output: {
path: './src/front_end/dist',
publicPath: '/',
filename: 'bundle.js'
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'root.jQuery': 'jquery',
'Promise': 'exports?global.Promise!es6-promise',
'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch',
}),
new webpack.DefinePlugin({
"require.specified": "require.resolve"
}),
]
};
The problem is that react-paginator's source hasn't been precompiled to a format that would work out of box. It still contains JSX. That's why the code fails for you.
To solve this you will have to compile the code yourself. You could try to add an include like this to your jsx loader definition:
include: path.join(__dirname, 'node_modules/react-paginator')
This should help webpack to compile the file for you.
On a related note I've developed an alternative component you could look into. See react-pagify. It should work without any fiddling on your part. It's more complicated to use by design, though.
I'm trying to setup a React project with react-css-modules, webpack and Hot Module Replacement. Everything is working like a charm but I can't get the CSS sourcemaps to work.
I followed this guide to make HMR work. It involves a BrowserSync setup to update the css file after Webpack writes it to disk.
I use (as suggested by react-css-modules) the ExtractTextPlugin to extract all of the css:
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style','css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!sass')
}
But if I change this to sourcemaps, as suggested here
loader: ExtractTextPlugin.extract('style', 'css?sourceMap!sass-loader outputStyle=expanded&sourceMap=true&sourceMapContents=true')
I get the error: "root" CSS module is undefined. in my browser console.
You can find my example repo here, but here's the full webpack config I'm using for development.
var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var WriteFilePlugin = require('write-file-webpack-plugin').default;
module.exports = {
entry: {
bundle: [
'webpack/hot/dev-server',
'webpack-hot-middleware/client',
'./index.js'
]
},
devtool: 'cheap-module-source-map',
debug: true,
devServer: devServer,
context: path.resolve(__dirname, './src'),
output: {
path: path.resolve(__dirname, './builds'),
filename: '[name].js',
publicPath: '/builds/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.OldWatchingPlugin(),
new WriteFilePlugin(),
new ExtractTextPlugin('[name].css', {
allChunks: true
})
],
module: {
loaders: [
{
test: /\.js$/,
loaders: ['react-hot', 'babel-loader'],
exclude: /node_modules/
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style','css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!sass')
}
]
},
resolve: {
extensions: ['', '.js', '.json']
}
};
How to make the sourcemap work?
Use this:
ExtractTextPlugin.extract('style','css?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!sass?sourceMap')
i.e. add the sourceMap param to both css & sass loaders. It said so in sass-loader docs.
This is how I have my css modules set up:
'css-loader?modules&sourceMap&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!',
I'm totally new to webpack and I'm doing my first configuration for a new project.
I'm trying to load my jsx/scss file but I've this problem:
var path = require('path');
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var node_modules_dir = path.resolve(__dirname, 'node_modules');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackPlugin = require('html-webpack-plugin');
var cssExtractTextPlugin = new ExtractTextPlugin("css", "index.css");
var staticPrefix = path.join(__dirname, 'src')
var distPath = path.join(__dirname, 'dist')
module.exports = {
devtool: 'eval',
//context: path.join(__dirname, staticPrefix),
entry: {
'app': ['webpack-hot-middleware/client', path.join(__dirname, 'src/app.jsx')],
'vendor': [
'bootstrap/js/dropdown',
'bootstrap/js/tab',
'bootstrap/js/tooltip',
'bootstrap/js/alert',
'jquery',
'react-router',
'react-bootstrap'
],
'myapp': path.join(__dirname, 'src/stylesheets/base.scss') //'stylesheets/base.scss'
},
output: {
path: distPath,
filename: '[name].js',
libraryTarget: 'var',
library: 'exports',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'root.jQuery': 'jquery'
}),
new ExtractTextPlugin('[name].css')
],
module: {
loaders: [
{
test: /\.js$/,
loader: ['babel'],
include: path.join(__dirname, staticPrefix),
exclude: /(vendor|node_modules)/
},
{
test: /\.jsx$/,
loader: ['babel'],
include: path.join(__dirname, staticPrefix),
exclude: /(vendor|node_modules)/
},
{
test: /\.scss$/,
include: path.join(__dirname, staticPrefix),
loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader-loader')
},
{
test: /\.(woff|woff2|ttf|eot|svg|png|gif|ico|jpg)($|\?)/,
loader: 'file-loader?name=' + '[name].[ext]'
}
]
},
postcss: function() {
return [autoprefixer];
},
resolve: {
modulesDirectories: [path.join(__dirname, staticPrefix), 'node_modules'],
extensions: ['', '.jsx', '.js']
},
};
The problem is that when I run: node_modules/.bin/webpack --config=webpack.config.dev it give me 2 errors:
ERROR in ./src/app.jsx
Module parse failed: /Users/work/Desktop/myapp-client/src/app.jsx Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import React from 'react';
| console.log('hello!’);
|
# multi app
ERROR in ./src/stylesheets/base.scss
Module parse failed: /Users/work/Desktop/myapp-client/src/stylesheets/base.scss Line 1: Unexpected token {
You may need an appropriate loader to handle this file type.
| body {
| background: black;
| }
Where I'm doing wrong ?
With babel 6 you need to include the babel react preset to transpile your .jsx files. You also need to add the babel es2015 preset to transpile ES2015, i.e. ES6, syntax:
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
loader: 'babel',
query: {
presets:[ 'react', 'es2015' ]
}
}
]
}
On a side note, if you tweak your regex in the test key, you don't need two loader entries (for the .js and .jsx files).
Make sure you install these presets separately:
npm i -D babel-preset-es2015 babel-preset-react
More info on the babel 6 changes can be found here