Rails 6 - Bootstrap - Webpacker Failed To Compile - ruby-on-rails

My google foo is failing my here folks. The issue is clearly the underscores in the MAX_UID which is easy enough to fix manually but not when I'm running the deployment.
Any ideas about what loader I need and where to configure this? It seems to be #babel/preset-env but I'm struggling to get this configured as a laoder
ERROR in ./node_modules/bootstrap/js/src/util/index.js 8:17
Module parse failed: Identifier directly after number (8:17)
File was processed with these loaders:
* ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| */
|
> const MAX_UID = 1_000_000;
| const MILLISECONDS_MULTIPLIER = 1000;
| const TRANSITION_END = 'transitionend';
# ./node_modules/bootstrap/js/src/alert.js 8:0-50 78:0-18
# ./app/javascript/js/bootstrap_js_files.js
# ./app/javascript/packs/application.js
# multi ./app/javascript/packs/application.js ./app/javascript/packs/application.scss
babel.config.js
module.exports = function (api) {
var validEnv = ['development', 'test', 'production', 'staging']
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',
{
targets: {
node: 'current'
}
}
],
(isProductionEnv || isDevelopmentEnv) && [
'#babel/preset-env',
{
forceAllTransforms: true,
useBuiltIns: 'entry',
corejs: 3,
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-transform-destructuring',
[
'#babel/plugin-proposal-class-properties',
{
loose: true
}
],
[
'#babel/plugin-proposal-object-rest-spread',
{
useBuiltIns: true
}
],
[
'#babel/plugin-proposal-private-methods',
{
loose: true
}
],
[
'#babel/plugin-proposal-private-property-in-object',
{
loose: true
}
],
[
'#babel/plugin-transform-runtime',
{
helpers: false
}
],
[
'#babel/plugin-transform-regenerator',
{
async: false
}
]
].filter(Boolean)
}
}

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)
}
}

A JavaScript error occurred in the main process. TypeError: electron.BrowserWindow.addDevToolsExtension is not a function

When I introduced devtron into electron, the program reported an error。
Uncaught Exception:
TypeError: electron.BrowserWindow.addDevToolsExtension is not a function
at Object.exports.install (/electron-quick-start/node_modules/devtron/api.js:13:35)
at App.<anonymous> (/electron-quick-start/main.js:6:24)
at App.emit (node:events:394:28)
I created electron for the first time. I cloned a project from GIT:
git clone https://github.com/electron/electron-quick-start
my code is like this
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path')
app.on("ready", () => {
require('devtron').install();
let mainWindow = new BrowserWindow({
width: 1600,
height: 1200,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
mainWindow.loadFile('index.html')
mainWindow.webContents.openDevTools(); // 自动打开inspector
ipcMain.on('message',(event,args) => {
console.log(arg)
})
})
my package.json is like this
{
"name": "electron-quick-start",
"version": "1.0.0",
"description": "A minimal Electron application",
"main": "main.js",
"scripts": {
"start": "nodemon --watch main.js --exec \"electron .\""
},
"repository": "https://github.com/electron/electron-quick-start",
"keywords": [
"Electron",
"quick",
"start",
"tutorial",
"demo"
],
"author": "GitHub",
"license": "CC0-1.0",
"devDependencies": {
"electron": "^15.3.1",
"nodemon": "^2.0.15"
}
}
I solved it with this answer,click me see more.
diff --git a/node_modules/devtron/api.js b/node_modules/devtron/api.js
index 3cdabe2..edf8b75 100644
--- a/node_modules/devtron/api.js
+++ b/node_modules/devtron/api.js
## -1,29 +1,27 ##
const electron = require('electron')
+const path = require('path')
-exports.install = () => {
- if (process.type === 'renderer') {
- console.log(`Installing Devtron from ${__dirname}`)
- if (electron.remote.BrowserWindow.getDevToolsExtensions &&
- electron.remote.BrowserWindow.getDevToolsExtensions().devtron) return true
- return electron.remote.BrowserWindow.addDevToolsExtension(__dirname)
- } else if (process.type === 'browser') {
+const resolve = (_dir) => path.resolve(process.cwd(), _dir)
+
+
+exports.install = (session) => {
+ if (process.type === 'renderer' || process.type === 'browser') {
console.log(`Installing Devtron from ${__dirname}`)
- if (electron.BrowserWindow.getDevToolsExtensions &&
- electron.BrowserWindow.getDevToolsExtensions().devtron) return true
- return electron.BrowserWindow.addDevToolsExtension(__dirname)
+ if (session.defaultSession.getAllExtensions &&
+ session.defaultSession.getAllExtensions().devtron) return true
+ return session.defaultSession.loadExtension(resolve(__dirname))
} else {
throw new Error('Devtron can only be installed from an Electron process.')
}
}
-exports.uninstall = () => {
- if (process.type === 'renderer') {
+exports.uninstall = (session) => {
+ if (process.type === 'renderer' || process.type === 'browser') {
console.log(`Uninstalling Devtron from ${__dirname}`)
- return electron.remote.BrowserWindow.removeDevToolsExtension('devtron')
- } else if (process.type === 'browser') {
- console.log(`Uninstalling Devtron from ${__dirname}`)
- return electron.BrowserWindow.removeDevToolsExtension('devtron')
- } else {
+ if (session.defaultSession.getAllExtensions &&
+ !session.defaultSession.getAllExtensions().devtron) return true
+ return session.defaultSession.removeExtension('devtron')
+ }else {
throw new Error('Devtron can only be uninstalled from an Electron process.')
}
}
diff --git a/node_modules/devtron/manifest.json b/node_modules/devtron/manifest.json
index 24613a4..295f752 100644
--- a/node_modules/devtron/manifest.json
+++ b/node_modules/devtron/manifest.json
## -4,8 +4,11 ##
"devtools_page": "static/devtron.html",
"content_scripts": [
{
- "matches": ["*"],
- "js": ["out/browser-globals.js"]
+ "matches": ["http://*/*", "https://*/*"],
+ "js": ["out/browser-globals.js"],
+ "unsafe-inline": true
}
- ]
+ ],
+ "manifest_version": 2,
+ "content_security_policy":"script-src 'self' object-src 'sha256-oUhBdPf7Ru2sGu4k6v1SmxAkpoPTuzvsLrUqElYwDRE='"
}

#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.

PostCSS CSSNext #media and color() not working with webpack 2

I'm upgrading a project from webpack 1 to 2, and am seeing some strange behavior with postcss-cssnext where some css next features, most notably color() functions and all my #media queries just aren't working anymore.
My webpack config with webpack 2 looks like this. What am I doing wrong here?
{
test: /\.css$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
localIndentName: 'localIdentName=[name]__[local]___[hash:base64:5]',
sourceMap: true,
modules: true,
importLoaders: 1
}
},
{
loader: 'postcss-loader',
options: {
plugins: [
postcssImport({ path: './app/css/common' }),
postcssCssnext({ browsers: ['> 1%', 'last 2 versions'] }),
postcssReporter({ clearMessages: true })
]
}
}
]
}
postcss-loader is probably responsible for this change (1.3.x).
According to doc, you should use a function for "plugins" option.
Or use an array but in a postcss.config.js file.
module.exports = {
module: {
rules: [
{
test: /\.css/,
use: [
…
{
loader: 'postcss-loader',
options: {
plugins: function () {
return [
postcssImport({ path: './app/css/common' }),
postcssCssnext({ browsers: ['> 1%', 'last 2 versions'] }),
postcssReporter({ clearMessages: true })
];
}
}
}
]
}
]
}
}
Or via postcss.config.js
module.exports = {
plugins: [
postcssImport({ path: './app/css/common' }),
postcssCssnext({ browsers: ['> 1%', 'last 2 versions'] }),
postcssReporter({ clearMessages: true })
]
}
(and in webpack)
module.exports = {
module: {
rules: [
{
test: /\.css/,
use: [
…
'postcss-loader',
]
}
]
}
}

Loading jEditable library in Webpack

I tried to include jQuery plugin Jeditable as a webpack module from bower. I use bower-webpack-plugin to include some libraries, but it doesn't work in this case.
Edit: I use this webpack config.
webpack.config.js
const BowerWebpackPlugin = require("bower-webpack-plugin");
module.exports = {
entry: './src/script/index.jsx',
output: {
filename: 'bundle.js',
publicPath: 'http://localhost:8090/assets'
},
devtool: 'evil-source-map',
module: {
loaders: [
{
test: /\.js[x]?$/,
loaders: ['react-hot', 'jsx', 'babel'],
exclude: /node_modules/
},
{
test: /\.scss$/,
loaders: [ 'style', 'css?sourceMap', 'sass?sourceMap' ]
}
]
},
plugins: [
new BowerWebpackPlugin()
],
externals: {
'react': 'React'
},
resolve: {
extensions: ['', '.js', '.jsx']
}
}
bower.json
{
"name": "Won",
"version": "0.0.1",
"description": "Internal app",
"main": "index.js",
"authors": [
"and"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
],
"devDependencies": {
"jquery": "~2.1.4",
"babel-polyfill": "~0.0.1",
"bootstrap": "~3.3.5",
"col-resizable": "*",
"datatables": "~1.10.8",
"immutable": "~3.7.4",
"jeditable": "~1.7.3",
"jquery-resizable-columns": "~0.2.3",
"jquery-ui": "~1.11.4",
"kefir": "~2.8.0",
"lodash": "~3.10.1"
}
}
At first I get error:
Uncaught TypeError: $(...).find(...).editable is not a function
Then I tried to add Jeditable plugin
var editable = require('jeditable') or
var editable = require('jquery.jeditable')
but i get errors like
Module not found: Error: Cannot resolve module 'jeditable' in ...
Then I tried
var editable = require('../../bower_components/jeditable/jquery.jeditable')
I get error
Uncaught ReferenceError: jQuery is not defined
(anonymous function) # jquery.jeditable.js:494
Then I tried to add Jquery:
var jQuery = require('../../bower_components/jeditable/js/jquery')
var editable = require('../../bower_components/jeditable/jquery.jeditable')
but I get error:
./bower_components/jeditable/js/jquery.js
Module build failed: SyntaxError: /Users/an/Won_webpack_25_08/bower_components/jeditable/js/jquery.js: 'with' in strict mode (2907:13)
2905 | var left = 0, top = 0, elem = this[0], results;
2906 |
> 2907 | if ( elem ) with ( jQuery.browser ) {
| ^
2908 | var absolute = jQuery.css(elem, "position") == "absolute",
2909 | parent = elem.parentNode,
2910 | offsetParent = elem.offsetParent,
When I add window.jQuery = $; it works now

Resources