Webpack require.ensure Error on --optimize--minimize - javascript

I need to do code splitting and load some React component and other script on-demand, I simply do it like:
<Route path="/journal" getComponent={function (nextState, cb) {
require.ensure([], function (require) {
cb(null, require("./components/Journal"));
})
}} />
In development, just run webpack it works just fine.
But for production build, I run webpack -p, then I always get error:
Uncaught TypeError: Cannot read property 'call' of undefined
at e (bootstrap a99e046…:50)
line 50 is:
// Execute the module function
modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
What could be the issue ?
My webpack config:
var webpack = require('webpack');
var merge = require('webpack-merge');
var validate = require('webpack-validator');
var parts = require('./webpack.parts');
var common = {
entry: {
vendor: ['react', 'react-dom', 'lodash'],
},
output: {
filename: "index.bundle.js",
path: __dirname + '/public/js/',
publicPath: __dirname + '/public/js/'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
minChunks: 3,
filename: "vendor.bundle.js"
})
]
};
var config;
switch(process.env.npm_lifecycle_event) {
case 'build':
config = merge(common,
{
devtool: 'source-map',
entry: {
app: [ __dirname + '/src/index.js']
},
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loaders: ["babel-loader"]}
]
}
},
parts.productionOptimize()
);
break;
default:
config = merge(
common,
{
devtool: 'eval-source-map',
entry: {
app: ['webpack-hot-middleware/client', __dirname + '/src/index.js']
},
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loaders: ["react-hot","babel-loader"]}
]
}
},
parts.devServer({
host: process.env.HOST,
port: process.env.PORT
})
);
}
module.exports = validate(config);
webpack.parts.js
var webpack = require('webpack');
exports.devServer = function(options) {
return {
devServer: {
historyApiFallback: true,
inline: true,
hot: true,
stats: 'errors-only',
host: options.host,
port: options.port
},
plugins: [
new webpack.HotModuleReplacementPlugin({
multistep: true
})
]
};
}
exports.productionOptimize = function () {
return {
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin()
]
}
}

I did it wrong, publicPath should not be absolute:
I change
publicPath: __dirname + '/public/js/'
to
publicPath: '/js/'

Related

web worker not able to communicate in webpack

I am using webpack and this is my webpack config file
const webpack = require("webpack");
const path = require("path");
const lazPerf = require("laz-perf");
console.log(lazPerf);
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "docs"),
},
resolve: {
fallback: {
fs: false,
},
},
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
{
test: /\.worker\.js$/,
exclude: /node_modules/,
use: "worker-loader",
},
],
},
devServer: {
port: 8080,
static: path.resolve(__dirname, "docs"),
hot: true,
},
mode: "development",
devtool: "cheap-module-source-map",
plugins: [
// commonjs({ include: /node_modules\/laz-perf/ }),
new webpack.DefinePlugin({
tree: {
leafCapacity: 16,
bufferCapacity: 16,
},
}),
],
};
And in index.js
this is my code:
import Worker from "./worker/fetcher.worker.js";
const fetchWorker = new Worker();
fetchWorker.postMessage("hello");
and this is fetcher.worker.js
onmessage = function (message) {
console.log(message);
};
this is my directory structure
I am not able to communicate and get that console from fetcher worker !!
Any help, please

How do I access process.env.VAR in Webpack 5?

I've never used Webpack before and I'm working on a project that's just vanilla JS and HTML. I'm having an issue accessing the values I set in .env. Here's my config.
const path = require("path");
const dotenv = require('dotenv');
var webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const Dotenv = require('dotenv-webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = () => {
env = dotenv.config().parsed;
const envKeys = Object.keys(env).reduce((prev, next) => {
prev[`process.env.${next}`] = JSON.stringify(env[next]);
return prev;
}, {});
return {
entry: {
main: './src/index.js'
},
output: {
path: path.join(__dirname, '../build'),
filename: '[name].bundle.js'
},
mode: 'development',
devServer: {
contentBase: "./src/",
publicPath: "./src/",
compress: true,
port: 9000,
overlay: true,
disableHostCheck: true
},
devtool: 'inline-source-map',
resolve: {
alias: {
process: "process/browser"
}},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.(png|svg|jpe?g|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'assets/'
}
}
]
},
{
test: /\.html$/,
use: {
loader: 'html-loader',
options: {
//attributes: ['img:src', ':data-src'],
minimize: true
}
}
}
]
},
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser',
}),
new Dotenv(),
new webpack.DefinePlugin(envKeys),
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html'
}),
]
}
};
As you can see, I'm using dotEnv, definePlugin, and even the dotEnv-webpack plugin. Unfortunately, none of these solutions seem to allow me to access process.env.originURL.
originURL=https://localhost:3000
I'm not importing or requiring anything in my javascript file, index.js. I'm assuming this should work, but the console tells me that process is undefined.
console.log(process.env.originURL);
How can I access process.env.originURL in my index.js?
It should work. Maybe you could try this version:
new Dotenv({ systemvars: true })
If it still doesn't work, please show your package.json, as well as you .env file (randomize the values of course). Is .env at the root of you app?

Issues importing a library

I've recently came across a interact.js, a library that I want to use in one of my projects, but I cant get it to work.
I've installed it via npm
npm install interactjs --save
It shows up in my package.json dependency as
"dependencies": {
"angular": "^1.6.4",
"angular-ui-router": "^0.4.2",
"interactjs": "^1.2.9"
}
And I've also imported it in main.js where I import other libs and modules
import 'interactjs';
The project being in angularjs, I've used some interact.js syntax inside a function within my controller, but I get the following error:
app.js:57837 Uncaught Error: Module parse failed: path\controller.js Unexpected token (207:48)
You may need an appropriate loader to handle this file type.
| drag() {
| let drag = document.querySelector('.draggable');
| interact(drag).draggable({ inertia: true; })
| }
|
at Object.__webpack_require__.constructor.options.count (app.js:57837)
at __webpack_require__ (app.js:658)
at fn (app.js:86)
at Object.__webpack_exports__.a (app.js:57778)
at __webpack_require__ (app.js:658)
at fn (app.js:86)
at Object.<anonymous> (app.js:57896)
at __webpack_require__ (app.js:658)
at fn (app.js:86)
at Object.module.exports (app.js:5219)
I'm guessing it has something to do with webpack and not the library itself ?
EDIT: webpack.config.js
const path = require('path');
const webpack = require('webpack');
/**
* Plugins
*/
const HtmlWebpackPlugin = require('html-webpack-plugin');
/**
* Env. vars
*/
const port = process.env.PORT || 3000;
const hostname = process.env.HOSTNAME || 'localhost';
const host = 'http://' + hostname + ':' + port;
const assetHost = process.env.ASSET_HOST || host + '/';
const paths = {
source: 'src',
dist: 'public'
};
module.exports = {
entry: {
app: [
path.resolve('src/main.js'),
'webpack-dev-server/client?' + host,
'webpack/hot/only-dev-server'
]
},
output: {
path: path.join(process.cwd(), 'public'),
filename: '[name].js',
chunkFilename: '[chunkhash].[name].js'
},
resolveLoader: {
modules: ['node_modules']
},
resolve: {
modules: [
'devtools',
'src',
'node_modules'
],
extensions: ['.ts', '.js', '.json', '.scss', '.css', '.html', '.jpg', '.png'],
alias: {
'game': path.resolve('src/modules/game')
}
},
node: {
global: true,
process: true,
console: true,
fs: 'empty'
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve('src/index.ejs'),
inject: 'head'
}),
new webpack.HotModuleReplacementPlugin()
],
devServer: {
inline: true,
port: port,
publicPath: assetHost, // Make sure publicPath always starts and ends with a forward slash.
contentBase: [
path.join(process.cwd(), paths.source),
path.join(process.cwd(), paths.dist)
],
clientLogLevel: 'none',
noInfo: true,
historyApiFallback: {
disableDotRule: true
}
},
module: {
rules: [
{
test: /\.html$/,
exclude: /node_modules/,
use: [
{
loader: 'html-loader'
}
]
},
{
test: /\.(jpe?g|gif|png|woff|woff2|eot|ttf|svg)$/,
use: [
{
loader: 'file-loader'
}
]
},
{
test: /\.scss$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader',
options: {
includePaths: [
// path.resolve('node_modules/xbem/src/'),
// path.resolve('src/themes/' + config.theme)
]
}
}
]
}
]
}
}

Webpack with Phantom/Casper/Spooky: Unable to Open File

My Spooky/Casper/Phantom project was working just fine. Then I tried to involve Webpack.
When I run the program, I get:
CasperError: Can't find module node_modules/spooky/lib/bootstrap/emit
[ { file: 'phantomjs://code/bootstrap.js',
line: 297,
function: 'patchedRequire' } ]
My file structure is as follows:
dist/
index.js
webpack.config.js
...
node_modules/
In my index.js:
import Spooky from 'spooky';
const spooky = new Spooky({
child: {
transport: 'http',
spooky_lib: 'node_modules/spooky/',
},
casper: {
logLevel: 'debug',
verbose: false
}
}, ...);
My webpack.config.js:
const path = require('path');
module.exports = {
context: __dirname,
entry: './index.js',
target: 'node',
output: {
path: path.join(__dirname, 'dist'),
filename: 'index.js',
publicPath: path.join(__dirname, 'dist')
},
devtool: 'source-maps',
node: {
__dirname: true
},
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
}
]
},
resolve: {
extensions: ['.js']
}
};

React Toolbox finding ~react-toolbox/lib/colors

Im having some issue trying to setting up the webpack with toolbox.
For some reason i dont know why its not working.
My webpack file looks like:
const path = require('path');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
context: __dirname,
devtool: 'inline-source-map',
entry: {
factigisVE: './static/js/bundles/factigisVE.js',
vendor: [
'webpack-hot-middleware/client'
]
},
output: {
path: path.join(path.join(__dirname, 'dist'), 'js'),
filename: '[name].js',
libraryTarget: "amd",
publicPath: '/'
},
resolve: {
extensions: ['', '.scss', '.css', '.js', '.json','.webpack.js', '.web.js', '.js', '.jsx'],
modulesDirectories: [
'node_modules',
path.resolve(__dirname, './node_modules')
]
},
module: {
loaders: [
{
test: /(\.js|\.jsx)$/,
exclude: /(node_modules)/,
loader: 'babel',
query: { presets: ['es2015', 'stage-0', 'react','stage-2'] }
}, {
test: /(\.scss|\.css)$/,
loader: ExtractTextPlugin.extract('style', 'css?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss!sass')
}
]
},
externals: [
function(context, request, callback) {
if (/^dojo/.test(request) ||
/^dojox/.test(request) ||
/^dijit/.test(request) ||
/^esri/.test(request)
) {
return callback(null, "amd " + request);
}
callback();
}
],
devServer: {
inline: true,
port: 443,
host: "127.0.0.1",
historyApiFallback: true
},
devtool: 'source-map',
postcss: [autoprefixer],
sassLoader: {
data: '#import "css/index.scss";',
includePaths: [path.resolve(__dirname, './static')]
},
plugins: [
new ExtractTextPlugin('../css/style.css', { allChunks: true }),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
})
]
};
And then my index.scss looks like:
#import "~react-toolbox/lib/colors";
$color-primary: $palette-blue-500;
$color-primary-dark: $palette-blue-700;
The errors that im having are:
Error: File to import not found or unreadable: ~react-toolbox/lib/colors
parent style sheet: I:/proyect/ve/static/css/index.scss on line 1 of static/css/index.scss
> #import "~react-toolbox/lib/colors";
Also my directory looks like: my directory
Any help on whats going on will be really appreciate.
Thanks !
I was able to resolve this problem by removing the ~ from the start of the import.
#import "react-toolbox/lib/colors";
The postcss-import plugin appears to have the same behvaior.

Categories