wrangler dev failed using #cfworker/web - npm

I'm trying to deploy a project on Cloudflare workers using wrangler. I'm using the #cfworker/web package for routing. I've only setup a route at / for testing but it doesn't seem to work.
Here's the dev output:
> wrangler dev
./node_modules/#cfworker/web/dist/application.js 31:30
Module parse failed: Unexpected token (31:30)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| }
| catch (err) {
> console.error(err?.stack ?? err);
| if (err instanceof HttpError) {
| return err.toResponse();
# ./node_modules/#cfworker/web/dist/index.js 3:0-33 3:0-33
# ./src/index.ts
Error: webpack returned an error. Try configuring `entry` in your webpack config relative to the current working directory, or setting `context = __dirname` in your webpack config.
my package.json:
{
"name": "my-project",
"main": "./src/index.ts",
"scripts": {
"dev": "wrangler dev",
"preview": "wrangler preview --watch",
"build": "wrangler build",
"publish": "wrangler publish"
},
"devDependencies": {
"#babel/cli": "^7.13.16",
"#babel/core": "^7.14.0",
"#babel/plugin-proposal-class-properties": "^7.13.0",
"#babel/plugin-proposal-nullish-coalescing-operator": "^7.16.5",
"#babel/plugin-proposal-optional-chaining": "^7.13.12",
"#babel/plugin-transform-runtime": "^7.13.15",
"#babel/preset-env": "^7.14.1",
"#babel/preset-typescript": "^7.13.0",
"#cloudflare/workers-types": "^2.2.2",
"babel-loader": "^8.2.2",
"typescript": "^4.2.4",
"webpack": "^5.36.2",
"webpack-cli": "^4.7.0"
},
"dependencies": {
"#cfworker/web": "^1.6.11"
}
}
my webpack.config.js:
const path = require('path')
module.exports = {
mode: 'production',
entry: './src/index.ts',
output: {
filename: 'worker.js',
path: path.join(__dirname, 'dist'),
},
performance: {
hints: false,
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json'],
},
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
'#babel/preset-typescript',
],
plugins: [
'#babel/plugin-proposal-class-properties',
'#babel/plugin-transform-runtime',
'#babel/plugin-proposal-optional-chaining',
'#babel/plugin-proposal-nullish-coalescing-operator',
],
},
},
],
},
}
I can't figure out if there's something wrong with my webpack config or if there something else.

I managed to get it working by changing the webpack config at line
exclude: /(node_modules|bower_components)/,
to
include: /(node_modules\\#cfworker\\web|src)/,
It seems that the #cfworker/web module is using optional chaining and nullish coalescing and was excluded from the babel-loader.

Related

You are running the esm-bundler build of Vue. It is recommended to configure your bundler

I am getting this error on my Vue 3 project:
You are running the esm-bundler build of Vue. It is recommended to configure your bundler to explicitly replace feature flag globals with boolean literals to get proper tree-shaking in the final bundle. See http://link.vuejs.org/feature-flags for more details.
webpack.mix.js
const mix = require ('laravel-mix');
const path = require ('path');
mix.webpackConfig ({
output: {
chunkFilename: 'js/chunks/[name].[chunkhash].js'
},
module: {
rules: [
{
test: /node_modules(?:\/|\\).+\.js$/,
loader: 'babel-loader',
options: {
presets: [['#babel/preset-env', {targets: 'last 2 versions, ie >= 10'}]],
plugins: ['#babel/plugin-transform-destructuring', '#babel/plugin-proposal-object-rest-spread', '#babel/plugin-transform-template-literals'],
babelrc: false
}
},
{
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /node_modules/
}
]
},
resolve: {
alias: {
vue: "vue/dist/vue.esm-bundler.js"
},
},
optimization: {
providedExports: false,
sideEffects: false,
usedExports: false
}
});
mix.js ("resources/js/entry-point.js", "public/js").vue({})
.postCss ("resources/css/app.css", "public/css", [
require ("tailwindcss"),
]);
mix.extract (['vue']);
if (mix.inProduction ()) {
mix
.version ();
}
In this case, it does not matter whether I set mix.webpackConfig or not.
This is package.json:
{
"private": true,
"scripts": {
"dev": "npm run development",
"development": "mix",
"watch": "mix watch",
"watch-poll": "mix watch -- --watch-options-poll=1000",
"hot": "mix watch --hot",
"prod": "npm run production",
"production": "mix --production"
},
"devDependencies": {
"#vue/compiler-sfc": "^3.0.5",
"autoprefixer": "^10.2.4",
"axios": "^0.21",
"cross-env": "^5.1",
"css-loader": "^5.0.2",
"eslint-plugin-vue": "^7.5.0",
"file-loader": "^6.2.0",
"laravel-mix": "^6.0.6",
"mini-css-extract-plugin": "^1.3.6",
"postcss": "^8.2.6",
"resolve-url-loader": "^3.1.2",
"tailwindcss": "^2.0.3",
"url-loader": "^4.0.0",
"vue-loader": "^16.1.2",
"babel-eslint": "^10.1.0",
"eslint": "^7.19.0",
"eslint-config-google": "^0.14.0",
"eslint-loader": "^4.0.2"
},
"dependencies": {
"vue": "^3.0.5",
"vue-router": "4.0.3"
}
}
I read the provided link, but I did not see a way to solve this issue.
The linked docs specify two configurable flags:
__VUE_OPTIONS_API__ (enable/disable Options API support, default: true)
__VUE_PROD_DEVTOOLS__ (enable/disable devtools support in production, default: false)
For Webpack, use the DefinePlugin to set these flags:
const webpack = require('webpack')
mix.webpackConfig ({
plugins: [
new webpack.DefinePlugin({
__VUE_OPTIONS_API__: false,
__VUE_PROD_DEVTOOLS__: false,
}),
],
})
webpack.config.js
const Webpack = require('webpack');
module.exports = (env, options) => {
return {
...,
module : {
...,
},
plugins : [
...,
new Webpack.DefinePlugin({ __VUE_OPTIONS_API__: true, __VUE_PROD_DEVTOOLS__: true }), // to remove warn in browser console: runtime-core.esm-bundler.js:3607 Feature flags __VUE_OPTIONS_API__, __VUE_PROD_DEVTOOLS__ are not explicitly defined...
...,
],
...,
};
};
Or alternative is to add 2 lines into app entry file:
globalThis.__VUE_OPTIONS_API__ = true;
globalThis.__VUE_PROD_DEVTOOLS__ = false;
For laravel-mix use
mix.webpackConfig(webpack => {
return {
plugins: [
new webpack.DefinePlugin({
__VUE_OPTIONS_API__: false,
__VUE_PROD_DEVTOOLS__: false,
}),
],
}
})
For Laravel 8 add .vue().
https://laravel.com/docs/8.x/mix#vue
Mix will automatically install the Babel plugins necessary for Vue single-file component compilation support when using the vue method. No further configuration is required
mix.js('resources/js/app.js', 'public/js')
.postCss('resources/css/app.css', 'public/css', [
//
])
.vue();

Vue 3 vendor bundle is bloated with #babel/parser/lib when vue.esm-bundler.js is used in webpack

I created a Vue 3 project and using webpack for bundling the package. Since I have in-DOM templates, I cannot go with the default #runtime-dom. So I have aliased Vue to point to vue.esm-bundler.js.
The issue I am facing is that, when I take a prod build, my vendor bundle is bloated with #babel/parser/lib.
Sample project to reproduce this issue is available here
Steps to follow:
npm install
npm run bundle
Open dist folder and see the Webpack bundle analyser report.
For ease of config, pasting the configs below.
webpack.config.js
const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
.BundleAnalyzerPlugin;
const { VueLoaderPlugin } = require("vue-loader");
const TerserPlugin = require("terser-webpack-plugin");
module.exports = (env, options) => {
const devMode = options.mode != "production";
return {
context: path.resolve(__dirname, "src"),
entry: {
"vue-bundle": "./entry/main.js",
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].js",
chunkFilename: "[name].js",
},
module: {
rules: [
{
test: /\.js$/,
exclude: [/node_modules/],
use: {
loader: "babel-loader",
options: {
presets: [
[
"#babel/preset-env",
{
targets: [">25%"],
debug: true,
corejs: "3.6.5",
useBuiltIns: false,
},
],
],
},
},
},
{
test: /\.vue$/,
use: "vue-loader",
},
],
},
plugins: [
new CleanWebpackPlugin(),
new VueLoaderPlugin(),
new BundleAnalyzerPlugin({
openAnalyzer: false,
analyzerMode: "static",
reportFilename: "webpack_bundle_analyser_report.html",
defaultSizes: "gzip",
}),
],
optimization: {
mangleWasmImports: true,
removeAvailableModules: true,
sideEffects: true,
minimize: devMode ? false : true,
minimizer: [
new TerserPlugin({
test: /\.js(\?.*)?$/i,
exclude: /\/node-modules/,
parallel: 4,
extractComments: false,
}),
],
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: "vendor-bundle",
chunks: "all",
},
},
},
},
devtool: devMode ? "eval-cheap-source-map" : false,
resolve: {
extensions: [".ts", ".js", ".vue", ".json"],
alias: {
vue: "vue/dist/vue.esm-bundler.js"
},
},
};
};
package.json
{
"name": "testPro",
"version": "1.0.0",
"private": true,
"scripts": {
"bundle": "webpack --mode=production --config webpack.config.js",
"bundle-dev": "webpack --mode=development --config webpack.config.js"
},
"devDependencies": {
"#babel/core": "^7.12.3",
"#babel/preset-env": "^7.12.1",
"#babel/preset-typescript": "^7.12.1",
"#vue/compiler-sfc": "^3.0.2",
"babel-loader": "^8.1.0",
"clean-webpack-plugin": "^3.0.0",
"core-js": "^3.6.5",
"regenerator-runtime": "^0.13.7",
"terser-webpack-plugin": "^5.0.3",
"vue-loader": "^16.0.0-beta.4",
"webpack": "^5.3.0",
"webpack-bundle-analyzer": "^3.9.0",
"webpack-cli": "^4.1.0"
},
"dependencies": {
"vue": "^3.0.2"
}
}
Entry file main.js
import { createApp } from 'vue';
import App from '../App.vue';
createApp(App).mount('#app');
Not able to get what I am missing.
I strongly believe it is a bug in Vue 3 so I submitted a bug report - you can track it here
...I reproduced it myself using Vue CLI just to eliminate the chance the problem is in your Webpack config
You have 2 options to workaround this issue:
If you don't need to release right now, just work on your project and wait for a fix (I'm pretty sure it will be fixed - Vue builds for a browser which include compiler does not depend on #babel/parser so it's clear Vue don't need it to work correctly inside browser)
Don't use in-DOM templates and template option (string templates) - put everything in .vue files, <template></template> blocks - Runtime + Compiler vs. Runtime-only. Then you don't need a build with compiler...
EDIT: removed the part about missing process.env.NODE_ENV as --mode param to Webpack CLI does exactly that...

Error: Module parse failed when using babel with webpack

When I'm trying to install babel to use it webpack and make the configuration, I face this error. I tried different versions from babel and webpack and I tried so many configurations, non of them worked and they keeping throw the same error.
Notice: I already have another plugins like webpack-server and webpack-html but I'm pretty sure they doesn't affect babel.
ERROR in ./node_modules/core-js/modules/es6.regexp.exec.js 1:3
Module parse failed: Unexpected character ' ' (1:3)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
# ./node_modules/core-js/es6/index.js 102:0-37
# ./node_modules/#babel/polyfill/lib/noConflict.js
# ./node_modules/#babel/polyfill/lib/index.js
# multi #babel/polyfill ./src/js/index.js
.babelrc file:
// projectname/.babelrc
{
"presets": [
[ "#babel/preset-env", {
"modules": false,
"targets": {
"browsers": [
"last 2 Chrome versions",
"last 2 Firefox versions",
"last 2 Safari versions",
"last 2 iOS versions",
"last 1 Android version",
"last 1 ChromeAndroid version",
"ie 11"
]
}
} ]
]
}
webpack.config.js file:
// webpack.config.js
const path = require( 'path' );
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
context: __dirname,
entry: ['#babel/polyfill', './src/js/index.js'],
output: {
path: path.resolve( __dirname, 'dist' ),
filename: 'js/bundle.js',
},
devServer: {
contentBase: './dist'
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html'
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
};
package.json file:
{
"name": "forkify",
"version": "1.0.0",
"description": "forkify project",
"main": "index.js",
"scripts": {
"dev": "webpack --mode development",
"build": "webpack --mode production",
"start": "webpack-dev-server --mode development --open"
},
"author": "Ahmed Hossam",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.6.4",
"#babel/core": "^7.6.4",
"#babel/preset-env": "^7.6.3",
"babel-loader": "^8.0.6",
"html-webpack-plugin": "^3.2.0",
"path": "^0.12.7",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.9.0"
},
"dependencies": {
"#babel/polyfill": "^7.6.0"
}
}

vue.js - dynamic imports results in error: Support for the experimental syntax 'dynamicImport' isn't currently enabled

I'm learning Vue.js with Webpack for the first time today and trying to get a router working with lazy/dynamic imports.
I want to use lazy/dynamic imports because I am rebuilding my content management system which has many, many pages that may or may not be used during the user's session, so loading the modules they need dynamically, when they need them, makes more sense with regards to my application.
My very basic router currently looks like this:
import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
function loadView(view) {
return () => import(/* webpackChunkName: "view-[request]" */ `#/views/${view}.vue`);
}
export default new Router({
routes: [
{
path: "/",
name: "dashboard",
component: loadView("Dashboard")
},
{
path: "/login",
name: "login",
component: loadView("Login")
}
]
});
However, I run into the following compilation error:
ERROR in ./src/router/index.js Module build failed (from
./node_modules/babel-loader/lib/index.js): SyntaxError:
...../src/router/index.js: Support for the experimental syntax
'dynamicImport' isn't currently enabled
With the additional note:
Add #babel/plugin-syntax-dynamic-import to the
'plugins' section of your Babel config to enable parsing.
And shows me which line is the problem, which is quite obvious anyway:
return () => import(/*..........
^
I recognise this error from when I was playing with Webpack on its own a few months ago, so I knew I had to install the dynamic import plugin to make this work.
This is what I installed:
npm install babel-plugin-syntax-dynamic-import
And I made this plugin available in my babel.rc configuration file and ran npm run dev to recompile everything:
{
"presets": [
[
"#babel/env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}
]
],
"plugins": ["#babel/plugin-syntax-dynamic-import"]
}
But I'm still getting the error and I still can't use dynamic importing features! Am I doing something wrong? Has anybody else had trouble with getting dynamic imports to work?
My webpack.config file:
'use strict';
const webpack = require('webpack');
const path = require('path');
const { VueLoaderPlugin } = require('vue-loader');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
mode: 'development',
entry: [
'./src/app.js'
],
devServer: {
hot: true,
watchOptions: {
poll: true
}
},
module: {
rules: [
{
test: /\.vue$/,
use: 'vue-loader'
},
{
test: /\.js$/,
use: 'babel-loader'
},
{
test: /\.scss$/,
use: [
'vue-style-loader',
'css-loader',
{
loader: 'sass-loader',
options: {
sourceMap: true,
outputStyle: 'compressed',
data: `
#import "./src/assets/scss/_variables.scss";
#import "./src/assets/scss/_mixins.scss";
`
}
}
]
}
]
},
resolve: {
alias: {
"#": path.resolve(__dirname, './src'),
"Components": path.resolve(__dirname, './src/components/')
}
},
optimization: {
minimizer: [new UglifyJsPlugin()],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new VueLoaderPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
})
]
}
My package.json file:
{
"name": "manage_v2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --config build/webpack.config.dev.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.18.0",
"vue": "^2.5.22",
"vue-router": "^3.0.2",
"vuex": "^3.1.0"
},
"devDependencies": {
"#babel/core": "^7.2.2",
"#babel/plugin-syntax-dynamic-import": "^7.2.0",
"#babel/preset-env": "^7.3.1",
"babel-loader": "^8.0.5",
"babel-plugin-dynamic-import-webpack": "^1.1.0",
"css-loader": "^2.1.0",
"html-webpack-plugin": "^3.2.0",
"node-sass": "^4.11.0",
"sass-loader": "^7.1.0",
"uglifyjs-webpack-plugin": "^2.1.1",
"vue-loader": "^15.6.2",
"vue-style-loader": "^4.1.2",
"vue-template-compiler": "^2.5.22",
"webpack": "^4.29.0",
"webpack-cli": "^3.2.1",
"webpack-dev-server": "^3.1.14"
}
}
I fixed the problem myself after many hours of frustration. I still don't know why the method that's used in the Babel, Webpack and Vue documentation doesn't work but I did get this working:
I first removed the plugin declaration from babel.rc file and then added an option to the babel loader in webpack.config file:
{
test: /\.js$/,
use: {
loader: "babel-loader",
options: {
plugins: [
"#babel/plugin-syntax-dynamic-import"
]
}
}
}
I hope this helps others.
You have the wrong plugin assignment:
"plugins": ["#babel/plugin-syntax-dynamic-import"]
Would be the correct format for that plugin.

ES6 Export with Babel

Clearly I'm missing something incredibly simple here, so I apologize in advance for the dumb question. I have no errors so it's difficult to Google.
I'm trying to export something, anything, from an npm package written in ES6, compiled with babel and webpack.
I followed this http://jamesknelson.com/using-es6-in-the-browser-with-babel-6-and-webpack/ for my webpack setup, leaving it mostly-identical, but find it below for reference. I made a test export repo just to make sure it wasn't anything in the code of the module I was trying to export; find that below as well. Any help would be greatly appreciated; at this point I feel like I'm taking crazy pills.
src/index.js
const test = "test";
export default test;
webpack.config.js
var path = require("path");
var webpack = require("webpack");
module.exports = {
entry: [
"babel-polyfill",
"./src/index"
],
output: {
//path: path.join(__dirname, "lib"),
//filename: "[name].js"
filename: "./lib/index.js"
},
// import bare, .js, and .jsx files
resolve: {
extensions: ["", ".js", ".jsx"]
},
devtool: "source-map",
module: {
loaders: [
{
loader: "babel-loader",
// only load src
include: [
path.resolve(__dirname, "src")
],
// only compile .js and .jsx files
test: /\.jsx?$/,
query: {
plugins: ["transform-runtime", "transform-decorators-legacy"],
//plugins: ["transform-decorators-legacy"],
presets: ["es2015", "stage-0", "react"]
}
},
]
},
debug: true
};
package.json
{
"name": "test-package",
"version": "0.0.1",
"description": "test",
"main": "lib/index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/xxx/xxx.git"
},
"scripts": {
"start": "webpack-dev-server"
},
"keywords": [
"es6"
],
"author": "me",
"license": "MIT",
"bugs": {
"url": "https://github.com/xxx/xxx/issues"
},
"homepage": "https://github.com/xxx/xxx#readme",
"dependencies": {
"babel-polyfill": "^6.5.0",
"babel-runtime": "^6.5.0"
},
"devDependencies": {
"babel-core": "^6.5.2",
"babel-loader": "^6.2.3",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-plugin-transform-runtime": "^6.5.2",
"babel-preset-es2015": "^6.5.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0",
"webpack": "^1.12.14",
"webpack-dev-server": "^1.14.1"
}
}
webpack -p
other project
npm i ../test-package
(verify actually installed, search for "test" in lib/index.js and find what should be the export)
import test from "test-package";
console.log(test);
console.log(Object.keys(test));
output: empty object, empty array
Why not trying
import * as test from "test-package";
And then
console.log(test);