I'm transferring the project from webpack to esbuild. when building a project, I get an error - esbuild

enter image description here
This is my esbuild config:
import * as esbuild from 'esbuild';
const isProduction = process.env.NODE_ENV === 'production';
async function startDevServer(context) {
await context.watch();
let { host, port } = await context.serve({
servedir: './public',
});
}
let ctx = await esbuild.context({
entryPoints: ['index.web.js'],
define: {
'process.env.NODE_ENV': 'production',
'window.IS_PRODUCTION': isProduction ? 'true' : 'false',
},
bundle: true,
minify: isProduction,
sourcemap: !isProduction,
assetNames: 'assets/[name]-[hash]',
format: 'iife',
tsconfig: 'tsconfig.web.json',
loader: {
'.png': 'file',
'.svg': 'file',
'.ttf': 'file',
'.eot': 'file',
'.woff': 'file',
'.woff2': 'file',
'.js': 'tsx',
},
jsx: 'automatic',
treeShaking: true,
resolveExtensions: [
'.web.tsx',
'.web.ts',
'.web.jsx',
'.web.js',
'.tsx',
'.ts',
'.jsx',
'.js',
],
outdir: './public/',
});
!isProduction && startDevServer(ctx);
I tried to install plugins, but it didn't work. When building, I get an error on importing types in package files.
"esbuild-plugin-babel-flow": "^0.0.5",
"esbuild-plugin-flow": "^0.3.2",

Related

Transpile Turbo/Rails Turbo for IE 11

I have a rails app using Hotwire (Turbo & Stimulus). I'm trying to use webpack and babel to transpile JS for ES5/IE11. Stimulus and Turbo don't support IE11 any more, so I'm also trying to explicitly transpile them and then add required polyfills. My understanding is even if they've already been transpiled, the result should still be valid ES6 that can be transpiled again.
For Stimulus this approach appears to work fine but for Turbo I get
Uncaught TypeError: t.tagName is undefined
ht turbo.es2017-esm.js:1308
My best guess is that this is because Turbo is distributed as UMD modules so my babel config isn't transpiling it correctly. What's the best way to approach this?
browserlist:
"browserslist": {
"production": [
"last 1 version",
"> 1%",
"IE 10"
],
webpack.config.js:
const path = require("path")
const webpack = require("webpack")
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const RemoveEmptyScriptsPlugin = require('webpack-remove-empty-scripts')
const CopyPlugin = require("copy-webpack-plugin");
const mode = process.env.NODE_ENV === 'development' ? 'development' : 'production'
module.exports = {
mode,
devtool: "source-map",
entry: {
application: [
"./app/frontend/application.js",
]
},
module: {
rules: [
{
test: /\.(js|ts)$/,
include: [
path.resolve(__dirname, 'node_modules/#hotwired/turbo'),
path.resolve(__dirname, 'node_modules/#hotwired/turbo-rails'),
path.resolve(__dirname, 'node_modules/#hotwired/stimulus'),
path.resolve(__dirname, 'node_modules/#stimulus/polyfills'),
path.resolve(__dirname, 'node_modules/#rails/actioncable'),
path.resolve(__dirname, 'app/frontend'),
],
use: ['babel-loader'],
},
{
test: /\.(png|jpe?g|gif|eot|woff|woff2|ttf|svg|ico)$/i,
type: 'asset/resource'
},
{
test: /\.(scss|css)/i,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
}
],
},
resolve: {
modules: ['node_modules']
},
output: {
filename: "[name].js",
// we must set publicPath to an empty value to override the default of
// auto which doesn't work in IE11
publicPath: '',
path: path.resolve(__dirname, "app/assets/builds"),
},
plugins: [
new RemoveEmptyScriptsPlugin(),
new MiniCssExtractPlugin(),
new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }),
new CopyPlugin({
patterns: [
{ from: "node_modules/html5shiv/dist/html5shiv.min.js", to: "vendor" },
{ from: "app/frontend/vendor/outerHTML.js", to: "vendor" },
{ from: "app/frontend/vendor/polyfill-output-value.js", to: "vendor" }
],
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
jquery: 'jquery',
'window.jQuery': 'jquery'
})
]
}
babel.config.js
module.exports = function(api) {
var validEnv = ['development', 'test', 'production']
var currentEnv = api.env()
var isDevelopmentEnv = api.env('development')
var isProductionEnv = api.env('production')
var isTestEnv = api.env('test')
if (!validEnv.includes(currentEnv)) {
throw new Error(
'Please specify a valid `NODE_ENV` or ' +
'`BABEL_ENV` environment variables. Valid values are "development", ' +
'"test", and "production". Instead, received: ' +
JSON.stringify(currentEnv) +
'.'
)
}
return {
presets: [
isTestEnv && [
'#babel/preset-env'
],
(isProductionEnv || isDevelopmentEnv) && [
'#babel/preset-env',
{
forceAllTransforms: true,
useBuiltIns: 'entry',
corejs: '3.21.1',
modules: false,
exclude: ['transform-typeof-symbol']
}
]
].filter(Boolean),
plugins: [
'babel-plugin-macros',
'#babel/plugin-syntax-dynamic-import',
isTestEnv && 'babel-plugin-dynamic-import-node',
'#babel/plugin-proposal-class-properties',
'#babel/plugin-proposal-object-rest-spread',
'#babel/plugin-proposal-private-methods',
'#babel/plugin-proposal-private-property-in-object',
'#babel/plugin-transform-regenerator',
'#babel/plugin-transform-runtime',
[
'#babel/plugin-transform-spread',
{
loose: true
}
]
].filter(Boolean)
}
}

#ngtools/webpack not compiling project code after migrating from Angular4 to Angular7

I migrated angular4 application to Angular7 and resolved the dev and prod builds but AOT build is not transpiling the application code(app.module). The main and polyfill bundle size is only 1 kb each. looking at the output console it seems it is not compiling any module.
webpack.config.js
:
/**
* #author: #AngularClass
*/
const webpack = require('webpack');
const helpers = require('./helpers');
const ngw = require('#ngtools/webpack');
const AssetsPlugin = require('assets-webpack-plugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const HtmlElementsPlugin = require('./html-elements-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const HMR = helpers.hasProcessFlag('hot');
const AOT = Boolean(process.env.BUILD_AOT) || helpers.hasNpmFlag('aot');
let METADATA = {
isDevServer: helpers.isWebpackDevServer(),
HMR
};
const sassConfig = require('./scss-config.common');
console.info(`[BUILD STARTED WITH ${AOT ? 'AOT' : 'WITHOUT AOT'}]`);
module.exports = function (options) {
const isProd = options.env === 'production';
const envString = isProd ? 'prod' : 'dev';
METADATA = Object.assign({}, METADATA, require(`./environment/meta-${envString}`));
return {
target: "web",
entry: {
'polyfills': './src/polyfills.browser.ts',
'main': AOT ? './src/main.browser.aot.ts' :
'./src/main.browser.ts'
},
resolve: {
alias: {
'tslib$': 'tslib/tslib.es6.js',
},
extensions: ['.ts', '.js', '.json'],
modules: [helpers.root('src'), helpers.root('node_modules')],
},
module: {
rules: [
{
test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
loader: '#ngtools/webpack'
},
{
test: /\.css$/,
use: [
`to-string-loader${isProd? '' : '?sourceMap'}`,
`css-loader?${JSON.stringify({ sourceMap: !isProd, importLoaders: 1 })}`,
'postcss-loader',
],
exclude: [helpers.root('src', 'styles')]
},
{
test: /\.scss$/,
use: [
`to-string-loader${isProd? '' : '?sourceMap'}`,
`css-loader?${JSON.stringify({ sourceMap: !isProd, importLoaders: 2 })}`,
'postcss-loader',
{
loader: 'sass-loader',
options: {
includePaths: sassConfig.includePaths,
sourceMap: !isProd
}
}
],
exclude: [helpers.root('src', 'styles')]
},
{
test: /\.html$/,
// use: { loader: 'html-loader' },
use: 'raw-loader',
exclude: [helpers.root('src/index.html')]
},
{
test: /\.(jpg|png|gif)$/,
use: 'file-loader'
},
{
test: /\.(eot|woff2?|svg|ttf)([\?]?.*)$/,
use: 'file-loader'
}
],
},
plugins: [
new webpack.ProvidePlugin({
'__assign': ['tslib', '__assign'],
'__extends': ['tslib', '__extends'],
}),
new AssetsPlugin({
path: helpers.root('dist'),
filename: 'webpack-assets.json',
prettyPrint: true
}),
new CheckerPlugin(),
new ContextReplacementPlugin( /(.+)?angular(\\|\/)core(.+)?/, helpers.root('./src'), {} ),
new CopyWebpackPlugin([
{ from: 'src/assets', to: 'assets' },
{ from: 'src/meta'}
],
isProd ? { ignore: [ 'mock-data/**/*' ] } : undefined
),
new HtmlWebpackPlugin({
minify: isProd ? {
removeComments: true,
collapseWhitespace: true,
collapseBooleanAttributes: true,
decodeEntities: true,
processConditionalComments: true,
} : false,
template: 'src/index.html',
title: METADATA.title,
metadata: METADATA,
chunksSortMode: "manual",
chunks: ['polyfills', 'vendor', 'main'],
inject: false
}),
new ScriptExtHtmlWebpackPlugin({
defaultAttribute: 'defer'
}),
new HtmlElementsPlugin({
headTags: require('./head-config.common')(envString)
}),
new LoaderOptionsPlugin({}),
new NormalModuleReplacementPlugin(
/facade(\\|\/)async/,
helpers.root('node_modules/#angular/core/src/facade/async.js')
),
new NormalModuleReplacementPlugin(
/facade(\\|\/)collection/,
helpers.root('node_modules/#angular/core/src/facade/collection.js')
),
new NormalModuleReplacementPlugin(
/facade(\\|\/)errors/,
helpers.root('node_modules/#angular/core/src/facade/errors.js')
),
new NormalModuleReplacementPlugin(
/facade(\\|\/)lang/,
helpers.root('node_modules/#angular/core/src/facade/lang.js')
),
new NormalModuleReplacementPlugin(
/facade(\\|\/)math/,
helpers.root('node_modules/#angular/core/src/facade/math.js')
),
new ngw.AngularCompilerPlugin({
tsConfigPath: helpers.root('tsconfig.webpack.json'),
entryModule: helpers.root('src', 'app/app.module#AppModule'),
sourceMap: true,
skipCodeGeneration: true
})
],
node: {
global: true,
crypto: 'empty',
process: true,
module: false,
clearImmediate: false,
setImmediate: false,
fs: 'empty'
},
optimization: {
splitChunks: {
cacheGroups: {
polyfills: {
name: 'polyfills',
chunks: (chunk) => {
return chunk.name === 'polyfills';
}
},
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
chunks: (chunk) => {
return chunk.name === 'main';
}
}
}
}
}
};
}
tsconfig.webpack.json:
{
"compilerOptions": {
"target": "es5",
"module": "es2015",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"noEmit": true,
"noEmitHelpers": true,
"importHelpers": true,
"paths": { "tslib": ["./node_modules/tslib/tslib.d.ts"] },
"baseUrl": "./",
"strictNullChecks": false,
"lib": [
"es2015",
"dom"
],
"typeRoots": [
"node_modules/#types"
],
"types": [
"hammerjs",
"node"
]
},
"exclude": [
"node_modules",
"dist",
"src/**/*.spec.ts",
"src/**/*.e2e.ts"
],
"awesomeTypescriptLoaderOptions": {
"forkChecker": true,
"useWebpackText": true
},
"angularCompilerOptions": {
"skipMetadataEmit": true,
"skipTemplateCodegen" : false
},
"compileOnSave": false,
"buildOnSave": false,
"atom": {
"rewriteTsconfig": false
}
}
Angular- V7
Webpack - 4
Node - 8.11.1
Finally, I managed to resolve this and the root cause was a silly one.
As my project is a legacy one so there are many unnecessary configurations and one such was "noEmit: true" in 'compilerOptions' in 'tsconfig.webpack.json' file.
After removing this property the artifacts are generating properly.

Vue cli. How to build with the same hash

i have a problem with hashes in vue cli build.
And now to the details.
I build my app, and in dist folder i see my files with names like
app.dsadas.js, chunk-1-dsadaas.js etc.. all looks good.
But i build my app in docker images, there may be 2 or more, and i need all this images with the same hashes in filenames, but it is not.
This 'webpack-md5-hash' plugin helped me with this problem, but its very old solution, works with warnings.
Help pls find solution for webpack 4.
This is my vue config file:
const path = require('path');
const VuetifyLoaderPlugin = require('vuetify-loader/lib/plugin');
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const productionGzipExtensions = ['js', 'css'];
function resolve(dir) {
return path.resolve(__dirname, dir);
}
module.exports = {
assetsDir: 'static',
runtimeCompiler: true,
lintOnSave: process.env.NODE_ENV !== 'production',
devServer: {
overlay: {
warnings: true,
errors: true,
},
},
configureWebpack: {
performance: {
hints: false,
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
vue$: 'vue/dist/vue.esm.js',
'#': resolve('src'),
utils: resolve('src/utils'),
api: resolve('src/api'),
defaultStates: resolve('src/store/modules/defaultStates'),
router: resolve('src/router'),
store: resolve('src/store'),
config: resolve('src/config'),
helpers: resolve('src/store/modules/helpers'),
constants: resolve('src/constants'),
mixins: resolve('src/mixins'),
},
},
plugins: [
new VuetifyLoaderPlugin(),
new CompressionWebpackPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(`\\.(${productionGzipExtensions.join('|')})$`),
threshold: 10240,
minRatio: 0.8,
}),
],
},
};

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.

How to load image by using webpack in .Net MVC

Currently using web pack in .net MVC with Angular 2 development. Hope someone can identify and explain what I have done wrong in the config.
Problem.
Unable to load images (404), check in browser and only 2 images being loaded.
In my project images folder,
webpack.config.js
var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var nodeExternals = require('webpack-node-externals');
var merge = require('webpack-merge');
var allFilenamesExceptJavaScript = /\.(?!js(\?|$))([^.]+(\?|$))/;
// Configuration in common to both client-side and server-side bundles
var sharedConfig = {
resolve: { extensions: [ '', '.js', '.ts' ] },
output: {
filename: '[name].js',
publicPath: '/dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
loaders: [
{ test: /\.ts$/, include: /ClientApp/, loader: 'ts', query: { silent: true } },
{ test: /\.html$/, loader: 'raw' },
{ test: /\.css$/, loader: 'to-string!css' },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url', query: { limit: 25000 } }
]
}
};
// Configuration for client-side bundle suitable for running in browsers
var clientBundleConfig = merge(sharedConfig, {
entry: { 'main-client': './ClientApp/boot-client.ts' },
output: { path: path.join(__dirname, './wwwroot/dist') },
devtool: isDevBuild ? 'inline-source-map' : null,
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [] : [
// Plugins that apply in production builds only
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin()
])
});
// Configuration for server-side (prerendering) bundle suitable for running in Node
var serverBundleConfig = merge(sharedConfig, {
entry: { 'main-server': './ClientApp/boot-server.ts' },
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, './ClientApp/dist')
},
target: 'node',
devtool: 'inline-source-map',
externals: [nodeExternals({ whitelist: [allFilenamesExceptJavaScript] })] // Don't bundle .js files from node_modules
});
module.exports = [clientBundleConfig, serverBundleConfig];
webpack.config.vendor.js
var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var extractCSS = new ExtractTextPlugin('vendor.css');
module.exports = {
resolve: {
extensions: ['', '.js']
},
module: {
loaders: [
{ test: /\.(png|jpg|ico|gif|woff|woff2|eot|ttf|svg)(\?|$)/, loader: 'url-loader' },
{ test: /\.css$/, loader: extractCSS.extract("style-loader", "css-loader") }
]
},
entry: {
vendor: [
'#angular/common',
'#angular/compiler',
'#angular/core',
'#angular/http',
'#angular/platform-browser',
'#angular/platform-browser-dynamic',
'#angular/router',
'#angular/platform-server',
'angular2-universal',
'angular2-universal-polyfills',
'animate.css/animate.min.css',
'bootstrap',
'bootstrap/dist/css/bootstrap.min.css',
'bootstrap/dist/js/bootstrap.min.js',
'es6-shim',
'es6-promise',
'font-awesome/css/font-awesome.min.css',
'html5shiv',
'isotope-layout',
'jquery',
'wowjs/dist/wow.min.js',
'zone.js',
'./js/main.js',
'./js/respond.min.js',
'./css/main.css',
'./css/prettyPhoto.css',
'./css/responsive.css'
],
},
output: {
path: path.join(__dirname, 'wwwroot', 'dist'),
publicPath: '/',
filename: '[name].js',
library: '[name]_[hash]'
},
plugins: [
extractCSS,
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DllPlugin({
path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
name: '[name]_[hash]'
})
, new CopyWebpackPlugin([{ from: 'images', to: './images' }])
].concat(isDevBuild ? [] : [
new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } })
])
};
_Layout.cshtml

Resources