I've ready many questions and articles on the subject, but nothing seems to work. My error is this:
SyntaxError: import declarations may only appear at top level of a module
It's a result of me being unable to properly transpile es6 code. Here's my webpack and .babelrc:
webpack:
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
var path = require('path')
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: [
'webpack-hot-middleware/client?reload=true',
path.join(__dirname, './app/index.js')
],
module: {
loaders: [{
test: [/\.js$/,/\.jsx$/],
loader: "babel-loader",
include: [
path.resolve(__dirname, "node_modules/flash-notification-react-redux"),
path.resolve(__dirname, "./app")
],
},{
test: /\.(css|scss)$/,
loader: ExtractTextPlugin.extract('css!sass')
},{
test: /\.(png|jpg)$/,
loader: 'url-loader?limit=8192'
}]
},
output: {
filename: 'index.bundle.js',
path: __dirname + '/dist',
publicPath: '/'
},
plugins: [
HTMLWebpackPluginConfig,
new ExtractTextPlugin('public/style.css', {
allChunks: true
}),
new webpack.HotModuleReplacementPlugin(),
]
}
.babelrc
{
presets: [ 'es2015', 'stage-0', 'react'],
plugins: ['transform-decorators-legacy']
}
I've tried various things (such as using 'babel-preset-es2015', as well as the stage-0 addition), but nothing seems to work.
This code in one of my Components:
import GrowlerComponent from 'flash-notification-react-redux'
is converted to this in index.bundle.js, which actually throws the error:
import GrowlerReducer from "./src/reducer/growler.reducer";
Related
I had a different thread here: React Build Tool and Dev Server
to setup React with Webpack. Seems like it is working but I have an issue with having the html page show the code from entry point app.js . I can see the code is in bundle.js. If I modify anything in app.js till the render method e.g enter a typo or something I see an error on console but nothing happens with the render() method. Not matter what I do there is no error and nothing shows but a blank page.
app.js
import React from 'react';
import ReactDOM from 'react-dom';
export default class App extends React.Component {
render() {
return (
ReactDOM.render(<h1>Render me!</h1>,
document.getElementById('app'))
);
}
}
Index.html
<!DOCTYPE html>
<html>
<head>
<!-- Bootstrap, latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src='bundle.js'></script>
</body>
</html>
So if I view page source it just shows just
and not the expected Render me!
And just in case below is my webpack.config
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: {
bundle: './src/app.js'
},
output: {
path: path.join(__dirname, '/dist'),
filename: 'bundle.js'
},
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-1']
}
}]
},
resolve: {
extensions: ['*', '.js', '.jsx']
}
};
Also this is from my package.json. I believe my bundle.js is being served from memory right now.
"scripts": {
"start": "webpack-dev-server --port 3000 --hot --inline",
"build": "webpack --progress --colors"
}
I run npm start to compile and start the server. I was expecting npm build will build to dist folder but it doesn't . For now I just want this working one way or the other so I can start coding.
And .babelrc
{
"presets":[
"es2017", "react"
]
}
You are using WebPack 3.x?
Try this config:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PreloadWebpackPlugin = require('preload-webpack-plugin');
const autoprefixer = require('autoprefixer');
const staticSourcePath = path.join(__dirname, 'static');
const sourcePath = path.join(__dirname);
const buildPath = path.join(__dirname, 'dist');
module.exports = {
devtool: 'source-map',
devServer: {
historyApiFallback: true,
contentBase: './'
},
entry: {
"index" :path.resolve(sourcePath, 'index.js')
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].[chunkhash].js',
publicPath: '/'
},
resolve: {
extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx'],
modules: [
sourcePath,
path.resolve(__dirname, 'node_modules')
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
}),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: 'vendor.[chunkhash].js',
minChunks: Infinity
}),
new webpack.LoaderOptionsPlugin({
options: {
postcss: [
autoprefixer({
browsers: [
'last 3 version',
'ie >= 10'
]
})
],
context: staticSourcePath
}
}),
new webpack.HashedModuleIdsPlugin(),
new HtmlWebpackPlugin({
template: path.join(__dirname, 'index.html'),
path: buildPath,
excludeChunks: ['base'],
filename: 'index.html',
minify: {
collapseWhitespace: true,
collapseInlineTagWhitespace: true,
removeComments: true,
removeRedundantAttributes: true
}
}),
new PreloadWebpackPlugin({
rel: 'preload',
as: 'script',
include: 'all',
fileBlacklist: [/\.(css|map)$/, /base?.+/]
}),
new webpack.NoEmitOnErrorsPlugin()
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react'],
}
},
include: sourcePath
},
{
test: /\.css$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{ loader: 'css-loader', options: { minimize: true } },
'postcss-loader',
'sass-loader'
]
})
},
{
test: /\.(eot?.+|svg?.+|ttf?.+|otf?.+|woff?.+|woff2?.+)$/,
use: 'file-loader?name=assets/[name]-[hash].[ext]'
},
{
test: /\.(png|gif|jpg|svg)$/,
use: [
'url-loader?limit=20480&name=assets/[name]-[hash].[ext]'
],
include: staticSourcePath
}
]
}
};
I want to exclude this from my webpack file, by using this line of code given to me below.
noParse: /node_modules\/localforage\/dist\/localforage.js/,
But no matter what I try I it keeps on saying errors like
ReferenceError: Unknown plugin "add-module-exports" specified in C:/..../node_modules\localforage\.babelrc
Here is my webpack config file:
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
devServer: {
historyApiFallback: true,
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.html'
})
]
};
You can use localForage 1.3+ version with webpack. You should add noParse in your config.
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
devServer: {
historyApiFallback: true,
},
module: {
noParse: /node_modules\/localforage\/dist\/localforage.js/,
rules: [{
test: /\.(js)$/,
exclude: /localforage/,
use: 'babel-loader'
}, {
test: /\.css$ / ,
use: ['style-loader', 'css-loader']
}]
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.html'
})
]
};
I am working on an Angular project and use Webpack bundler. Everything was working fine until Webpack started to ignore my changes to Typescript files. When I change a Typescript file, Webpack first says:
[WDS] App updated. Recompiling...
followed by:
[WDS] Nothing changed.
Also, killing webpack-dev-server and rebuilding the sources doesn't make any difference. The changes I make to TS files are not applied in any way.
EDIT: Loader setup on request (which is exactly the same as in the Angular Developer Guide):
webpack.common.js:
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');
module.exports = {
entry: {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
},
resolve: {
extensions: ['', '.js', '.ts']
},
module: {
loaders: [
{
test: /\.ts$/,
loaders: ['awesome-typescript-loader', 'angular2-template-loader']
},
{
test: /\.html$/,
loader: 'html'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file?name=assets/[name].[hash].[ext]'
},
{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
loader: ExtractTextPlugin.extract('style', 'css?sourceMap')
},
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'raw'
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),
new HtmlWebpackPlugin({
template: 'src/index.html'
})
]
};
webpack.dev.js:
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');
module.exports = webpackMerge(commonConfig, {
devtool: 'cheap-module-eval-source-map',
output: {
path: helpers.root('dist'),
publicPath: 'http://localhost:8080/',
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
plugins: [
new ExtractTextPlugin('[name].css')
],
devServer: {
historyApiFallback: true,
stats: 'minimal'
}
});
I set resolve.alias in webpack.config.js
alias: {
'$': 'jquery',
'_': 'underscore'
}
and require modules in my javascript file like this.
var $ = require('$');
var _ = require('_');
then there comes an error
Module not found: Error: Cannot resolve module '$'
I try to display error details and I find out that it still try to looking for modules named $ or _, not jquery or underscore.
So why doesn't the alias config work? Do I set a wrong config?
webpack.config.js
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var config = require('../config');
var projectRoot = path.resolve(__dirname, '../');
var buildPath = path.resolve(__dirname, 'demo');
module.exports = {
// eval-source-map is faster for development
devtool: '#eval-source-map',
entry: {
miceui: ['webpack-dev-server/client?http://localhost:3000',
'webpack/hot/dev-server',
path.resolve(projectRoot, 'index')]
},
output: {
path: buildPath,
filename: '[name].js'
},
plugins: [
new webpack.DefinePlugin({
'process.env': config.dev.env
}),
new ExtractTextPlugin('[name].css'),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
})
],
module: {
loaders: [
{ test: /\.htm(l?)$/, loader: 'html-loader' },
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') },
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.(png|jpg|gif)$/, loader: 'url-loader?limit=8192' }
]
},
resolve: {
extensions: ['', '.js', '.jsx', '.coffee', '.html', '.css', '.scss'],
alias: {
'$': 'jquery',
'_': 'underscore'
}
}
};
The follow production webpack.config file mostly works (builds, runs ok), but one nagging problem. I set up vendor and app js outputs precisely to separate vendor code (since those don't change very often). However, with the .config setup, even if there is no change, I always get a different chunk hash for vendor and app.js. I must be setting this wrong somehow but I have no idea what it could be. Please help!
var path = require('path');
var webpack = require('webpack');
var node_modules_dir = path.resolve(__dirname, 'node_modules');
var AssetsPlugin = require('assets-webpack-plugin');
var ChunkManifestPlugin = require('chunk-manifest-webpack-plugin');
var app_dir = path.join(__dirname, 'app');
var config = {
entry: {
vendors: ['react', 'react-dom', 'moment'],
app: path.resolve(__dirname, 'app/Main.js')
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[chunkhash].js',
chunkFilename: '[name].[chunkhash].js'
},
module: {
loaders: [{
test: /\.jsx?$/, // A regexp to test the require path. accepts either js or jsx
exclude: [node_modules_dir],
loader: 'babel', // The module to load. "babel" is short for "babel-loader"
},
// LESS
{
test: /\.less$/,
loader: 'style!css!less'
},
{
test: /\.css$/, // Only .css files
loader: 'style!css' // Run both loaders
},
{
test: /\.(png|jpg)$/,
loader: 'url?limit=25000'
},
{ test: /\.gif$/, loader: "url-loader?mimetype=image/png" },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&minetype=application/font-woff" },
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader?name=[name].[ext]" }
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: "vendors",
minChunks: Infinity
}),
new AssetsPlugin({
filename: 'webpack-assets.js',
path: path.resolve(__dirname, 'dist'),
processOutput: function (assets) {
return 'window.staticMap = ' + JSON.stringify(assets);
}
}),
new ChunkManifestPlugin({
filename: "chunk-manifest.json",
manifestVariable: "webpackManifest"
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': '"production"'
},
'__appSettings': {
'apiGatewayDomain': '"http://localhost:8088"',
'enableDevTools': false,
'enableReduxLogger': false
},
__version: JSON.stringify(require(__dirname +"/package.json").version)
}),
new webpack.ProvidePlugin({
'fetch': 'imports?this=>global!exports?global.fetch!isomorphic-fetch',
'configureApplicationStore': 'exports?configureStore!' + app_dir + '/global/redux/ConfigureStore.prod.js'
})
]
};
module.exports = config;
If there are other glaring issues with this setup, please let me know as well. Thanks!
use the "key sort" to fixed vendor.
you entry just like this:
entry: {
a_vendors: ['react', 'react-dom', 'moment'],
z_app: path.resolve(__dirname, 'app/Main.js')
},
the vendor will fixed.
more detail:
https://github.com/webpack/webpack/issues/1315#issuecomment-247269598
https://github.com/webpack/webpack/pull/2998