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
Related
I'm trying to make a real time shooter game on the web using ThreeJS and Rapier. Rapier is a physics engine written in rust and can be used in JS using the WASM module. Now in development webpack-dev-server and HMR are really a god given tool, if it works. The RAPIER WASM module gets loaded but from the wrong port. My HTTP server runs on http://localhost:8080 but the devserver on -:9000. The fetch mechanism that webpack uses to get the WASM doesn't configure the port for the fetch. Is this a bug or misconfiguration on my end?
My webpack.config.js:
const dotenv = require('dotenv');
dotenv.config();
const path = require('path');
const zlib = require('zlib');
const CompressionPlugin = require('compression-webpack-plugin');
const ThreadsPlugin = require('threads-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const WebpackBar = require('webpackbar');
const { WebpackManifestPlugin: ManifestPlugin } = require('webpack-manifest-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const DEBUG = process.env.NODE_ENV !== 'production';
const FILENAME = DEBUG ? '[name]' : '[name].[contenthash]';
const CHUNK_FILENAME = DEBUG ? '[name]' : '[id].[contenthash]';
module.exports = {
mode: DEBUG ? 'development' : 'production',
entry: { bundle: path.join(__dirname, 'resources/js/bundle.js') },
output: {
path: path.join(__dirname, 'public'),
filename: FILENAME + '.js',
chunkFilename: CHUNK_FILENAME + '.js',
publicPath: '',
clean: true,
},
module: {
rules: [
{
test: '/\.m?js$/',
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
{ test: /\.(frag|vert)$/, use: 'raw-loader' },
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 2 } },
'postcss-loader',
'sass-loader',
]
},
{ test: /\.(png|svg|jpg|jpeg|webm|gif)$/i, type: 'asset/resource' },
{ test: /\.(woff|woff2|eot|ttf|otf)$/i, type: 'asset/resource' },
{ test: /\.svelte$/, use: { loader: 'svelte-loader', options: {
emitCss: false,
hotReload: DEBUG,
compilerOptions: { dev: DEBUG },
hotOptions: {
preserveLocalState: false,
noReload: false, // prevent reload after fatal error
acceptAccesssors: true,
acceptNamedExports: true
}
} } },
{ test: /node_modules\/svelte\/.*\.mjs$/, resolve: { fullySpecified: false } }
]
},
plugins: [
new CopyPlugin({ patterns: [
// { from: './resources/images', to: 'images' },
{ from: './resources/textures', to: 'textures' },
{ from: './resources/scenes', to: 'scenes' },
] }),
new ManifestPlugin(),
new MiniCssExtractPlugin({
filename: FILENAME + '.css',
chunkFilename: CHUNK_FILENAME + '.css'
}),
// new ThreadsPlugin(),
new WebpackBar(),
].concat(DEBUG ? [] : [
new CompressionPlugin({
filename: '[path][base].gz',
algorithm: 'gzip',
test: /\.(js|css|html|svg)$/,
threshold: 10240,
minRatio: 0.8,
}),
new CompressionPlugin({
filename: '[path][base].br',
algorithm: 'brotliCompress',
test: /\.(js|css|html|svg)$/,
compressionOptions: {
params: {
[zlib.constants.BROTLI_PARAM_QUALITY]: 11,
},
},
threshold: 10240,
minRatio: 0.8,
})
]),
optimization: {
minimize: true,
minimizer: [ new TerserPlugin(), new CssMinimizerPlugin() ],
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
chunks: 'all'
}
}
}
},
devServer: {
port: 9000,
static: path.join(__dirname, 'public'),
hot: true,
client: {
overlay: {
errors: true,
warnings: false,
},
progress: true,
reconnect: 10,
webSocketURL: {
hostname: 'localhost',
port: 9000,
}
},
compress: true
},
devtool: DEBUG ? 'inline-source-map' : false,
experiments: {
asyncWebAssembly: true
}
};
I've googled a fair bit for solutions but so far I haven't found anything that looks like my particular issue.
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?
I'm currently using TS + React to make a simple application with some API requests to a server. When I try to use io-ts to decode the response, webpack responds with Module not found: Error: Can't resolve '../shared/Response' - if I remove the usage of io-ts to decode the response, I don't get that error.
My folder structure is
src
client
PlayerTimer.tsx
<skipped>
server
<skipped>
shared
Phase.d.ts
Response.d.ts
Phase.d.ts contains the following:
import * as t from 'io-ts';
export const PhaseDecode = t.union([
t.literal(1),
t.literal(2),
t.literal(3),
t.literal(4),
t.literal(5),
]);
export type Phase = t.TypeOf<typeof PhaseDecode>
Response.d.ts contains the following:
import * as t from 'io-ts';
import { DateFromISOString as IoDate } from 'io-ts-types/DateFromISOString';
import { PhaseDecode } from './Phase';
const ApiResponseDecode = t.type({
turnNumber: t.number,
phase: PhaseDecode,
breakingNews: t.union([t.string, t.null]),
active: t.boolean,
phaseEnd: IoDate
});
type ApiResponse = t.TypeOf<typeof ApiResponseDecode>
export { ApiResponseDecode, ApiResponse as default };
PlayerTimer.tsx contains a bunch of React components, but this is reproducible with just the following code at the top
import { ApiResponseDecode } from '../shared/Response';
const temp = {};
if (ApiResponseDecode.is(temp)) {
console.log('Webpack fails');
}
My webpack config is:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const outputDirectory = 'dist';
module.exports = {
entry: ['babel-polyfill', './src/client/index.tsx'],
output: {
path: path.join(__dirname, outputDirectory),
filename: './js/[name].bundle.js'
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
enforce: 'pre',
test: /\.js$/,
loader: 'source-map-loader'
},
{
test: /\.less$/,
use: [
{ loader: 'style-loader' },
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: './Less',
hmr: process.env.NODE_ENV === 'development',
},
},
{ loader: 'css-loader' },
{
loader: 'less-loader',
options: {
strictMath: true,
noIeCompat: true,
}
},
]
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
],
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000'
},
]
},
resolve: {
extensions: ['*', '.ts', '.tsx', '.js', '.jsx', '.json', '.less']
},
devServer: {
port: 3000,
open: true,
hot: true,
historyApiFallback: true,
proxy: {
'/api/**': {
target: 'http://localhost:8050',
secure: false,
changeOrigin: true
}
}
},
plugins: [
new CleanWebpackPlugin([outputDirectory]),
new HtmlWebpackPlugin({
template: './public/index.html',
favicon: './public/favicon.ico',
title: 'Test application',
}),
new MiniCssExtractPlugin({
filename: './css/[name].css',
chunkFilename: './css/[id].css',
}),
new CopyPlugin([
{ from: './src/client/Assets', to: 'assets' },
])
],
};
I fixed this by moving the type definitions and the io-ts definitions into separate files. I don't really understand why that works but I'll add this incase someone else finds this
I've recently tried to add proper code splitting for the first time to one of my projects.
It's worked, however I think it's worked a little TOO well!
When I run bundle-analyser, my dist folder contains a bunch of other bundles that contain snapshots and test files and I can't find any information that would explain why this is happening!
here is my webpack.config.base.js
const path = require('path');
const postcssNested = require('postcss-nested');
const postcssSimpleVars = require('postcss-simple-vars');
const postcssPresetEnv = require('postcss-preset-env');
const postcssImport = require('postcss-import');
const postcssFor = require('postcss-for');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractCssPluginConfig = new ExtractTextPlugin({
filename: '[name].[hash].css',
disable: false,
});
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
inject: 'body',
});
module.exports = {
entry: {
main: './src/index.jsx',
},
output: {
path: path.resolve('_dist'),
chunkFilename: '[name].[hash].bundle.min.js',
filename: '[name].[hash].min.js',
publicPath: '/',
},
module: {
rules: [
{
test: /\.(js|jsx)?$/,
loader: 'babel-loader',
exclude: /node_modules\/(?!(dom7|ssr-window|swiper)\/).*/,
},
{
test: /\.css$/,
loader: 'style-loader',
},
{
test: /\.css$/,
loader: 'css-loader',
query: {
modules: true,
importLoaders: 1,
localIdentName: '[path]___[name]__[local]___[hash:base64:5]',
},
},
{
test: /\.css$/,
loader: 'postcss-loader',
options: {
plugins: () => [
postcssNested,
postcssImport,
postcssFor,
postcssPresetEnv({
browsers: '>1%',
autoprefixer: {
grid: true,
browsers: ['>1%'],
},
insertBefore: {
'all-property': postcssSimpleVars,
},
}),
],
},
},
{
test: /\.(png|jp(e*)g|svg)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8000,
name: 'images/[hash]-[name].[ext]',
},
}],
},
{
test: /\.(woff|woff2|ttf|eot|otf)$/,
use: 'file-loader?name=fonts/[name].[ext]',
},
{
test: /\.(pdf)$/,
use: [{
loader: 'url-loader',
options: { limit: 8000, name: 'documents/[hash]-[name].[ext]' },
}],
},
],
},
resolve: {
extensions: ['.js', '.jsx', '.css', '.svg'],
modules: [path.resolve('./node_modules')],
alias: {
Pages: path.resolve(__dirname, 'src/pages/'),
Sections: path.resolve(__dirname, 'src/sections/'),
Components: path.resolve(__dirname, 'src/components/'),
Images: path.resolve(__dirname, 'src/images/'),
Downloads: path.resolve(__dirname, 'src/downloads/'),
Services: path.resolve(__dirname, 'src/services/'),
Enum: path.resolve(__dirname, 'src/enum/'),
Data: path.resolve(__dirname, 'src/data/'),
Utils: path.resolve(__dirname, 'src/utils/'),
Config: path.resolve(__dirname, 'src/config/'),
},
},
plugins: [
ExtractCssPluginConfig,
HtmlWebpackPluginConfig,
],
};
and here is my webpack.config.build.js
const webpack = require('webpack');
const merge = require('webpack-merge');
const WebpackCleanupPlugin = require('webpack-cleanup-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const baseConfig = require('./webpack.config.base');
const WebpackCleanupPluginConfig = new WebpackCleanupPlugin({
exclude: ['webpack.stats.json'],
quiet: true,
});
const CopyWebpackPluginConfig = new CopyWebpackPlugin([
{ from: './src/documents', to: './documents' },
]);
module.exports = () => {
const DefinePluginConfig = new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production'),
});
return (
merge(baseConfig, {
optimization: {
runtimeChunk: 'single',
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'initial',
enforce: true,
},
},
},
noEmitOnErrors: true,
concatenateModules: true,
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: false,
}),
],
},
plugins: [
DefinePluginConfig,
WebpackCleanupPluginConfig,
CopyWebpackPluginConfig,
],
})
);
};
I've tried adding a regex that matches any files with .test.js/jsx and .snap to my module.rules object but that did nothing.
Any help would be greatly appreciated!
If your test files are in a different directory, you might want to consider adding exclude property within the modules rules for js files.
Refer the following document: https://webpack.js.org/configuration/module/?_sm_au_=iVVKrMW7ZsbHQPbq#rule-exclude
or the following example: https://webpack.js.org/configuration/?_sm_au_=iVVKrMW7ZsbHQPbq#options
Another solution would be to use the IgnorePlugin. Docs for IgnorePlugin here: https://webpack.js.org/plugins/ignore-plugin/?_sm_au_=iVVKrMW7ZsbHQPbq
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']
}
};