swc-project / swc-loader Goto Github PK
View Code? Open in Web Editor NEWMoved to https://github.com/swc-project/pkgs
License: MIT License
Moved to https://github.com/swc-project/pkgs
License: MIT License
It seems that this code is not failsafe
let loaderOptions = (typeof this.getOptions === 'function' ? this.getOptions() : require('loader-utils').getOptions(this)) || {};
That is the only code that really changed since 0.2.1
Before it was
let loaderOptions = this.getOptions() || {};
So either revert back to that or make the code failesafer.
i want to target browsers that support es6 modules, but i didn't found any option how to do this, only way i see is ctrl+c, ctrl+v all browsers from can i use, but it looks terrible
thread '<unnamed>' panicked at 'failed to parse
TPas a version: invalid digit found in string', crates/swc_ecma_preset_env/src/version.rs:20:43 note: run with
RUST_BACKTRACE=1 environment variable to display a backtrace
function makeLoader() {
return function (source, inputSourceMap) {
......
let loaderOptions = this.getOptions() || {};
......
}
}
this.getOptions get supported from webpack5
so,we must hack this with the following code
var utils = require('loader-utils')
function makeLoader() {
return function (source, inputSourceMap) {
......
// let loaderOptions = this.getOptions() || {};
let loaderOptions = utils.getOptions(this)
......
}
}
almost all our swc-plugin dependencies recently upgraded to use [email protected] which maps to @swc/[email protected] ~ according to https://swc.rs/docs/plugin/selecting-swc-core
when we try to upgrade @swc/core and the plugins to latest, we are seeing following errors:
Module build failed (from ./node_modules/swc-loader/src/index.js):
Error: failed to handle: called `Result::unwrap()` on an `Err` value: PoisonError { .. }
Hi! I'm trying to replace ts-loader
with swc-loader
in my app to speed up building. And I found that the replacement cause unexpected result in code execution order. Here's the reproduction repository: https://github.com/JerryChan31/swc-loader-context
Reproduction steps:
pnpm install
on branch main
.git checkout ts-loader
npm run reproduce
git checkout swc-loader
npm run reproduce
And you can see the output of the first npm run reproduce
is:
a.js entry
d.js constructor
d.js init
a.js before B
B.js exec
and the second one:
d.js constructor
a.js entry
d.js init
a.js before B
B.js exec
It would be grateful to know what cause the difference. Thank you!
When using swc, there is an option for providing the filename which can be passed down to plugins, but when using the swc-loader, the filename is not passed automatically as in the way babel-loader
does it.
This makes it impossible for swc plugins using swc-loader to know the current filename and path being processed and have logic around that, along with all the other swc programatic options that could be useful to plugins.
thread '<unnamed>' panicked at 'index out of bounds: the len is 0 but the index is 0', /Users/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/sourcemap-6.0.1/src/builder.rs:84:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
fatal runtime error: failed to initiate panic, error 5
[1] 57707 abort npx webpack
Are there any plans on adding an option to the loaders to point to a swcrc configuration file similar to how babel does it?
https://babeljs.io/docs/en/options#configfile
When I set jsx: true, the default transformer is always React.createElement in my vue 2.x project, please help to resolve this problem, thanks.
@babel/helper-module-imports
permits import statements with no identifier to establish dependencies between files without exposing a javascript expression for that import.
https://babeljs.io/docs/en/babel-helper-module-imports
Common usage looks like
import 'bootstrap';
swc / swc-loader doesn't recognize this form of import statement, and throws.
Module parse failed: Unexpected token
A dependency should be established between the parent and referenced file; no javascript expression representing the imported resource should be generated.
First of all, thanks for developing such a great tool as SWC!
Talk directly from the code:
// main.ts (entry file)
const merge = <T extends object, U extends object>(target1: T, target2: U) => {
return { ...target1, ...target2 };
};
const result = merge({ name: 'Ian' }, { age: 24 });
// eslint-disable-next-line no-console
console.log(result);
// webpack.config.ts
const config: Configuration = {
...
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'swc-loader',
options: {
minify: true,
jsc: {
minify: {
compress: true,
mangle: true,
},
parser: {
syntax: 'typescript',
tsx: true,
decorators: true,
dynamicImport: true,
},
target: 'es5',
},
},
},
],
},
],
},
};
Compile the results:
default terser compression has been turned off.
/******/ (() => { // webpackBootstrap
/******/ "use strict";
var __webpack_exports__ = {};
function e(e,r,n){return r in e?Object.defineProperty(e,r,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[r]=n,e}var r,n,t=function(r){for(var n=1;n<arguments.length;n++){var t=null!=arguments[n]?arguments[n]:{},o=Object.keys(t);"function"==typeof Object.getOwnPropertySymbols&&(o=o.concat(Object.getOwnPropertySymbols(t).filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),o.forEach(function(n){e(r,n,t[n])})}return r}({},r={name:"Ian"},n={age:24});console.log(t);
/******/ })()
;
//# sourceMappingURL=main.9a6e608b.js.map
Compile results using TerserPlugin.swcMinify
:
inside the plugin will call the
swc.minify('...', { module: false, ecma: 2015, compress: { ecma: 2015 }, mangle: true, sourceMap: true })
method of @swc/core.
(()=>{"use strict";var e={};function r(e,r,n){return r in e?Object.defineProperty(e,r,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[r]=n,e}var n,t,o=function(e){for(var n=1;n<arguments.length;n++){var t=null!=arguments[n]?arguments[n]:{},o=Object.keys(t);"function"==typeof Object.getOwnPropertySymbols&&(o=o.concat(Object.getOwnPropertySymbols(t).filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),o.forEach(function(n){r(e,n,t[n])})}return e}({},{name:"Ian"},{age:24});console.log(o)})();
//# sourceMappingURL=main.4def3736.js.map
It is obvious that swc-loader left uncleared comments.
I will be grateful for any help you can provide!
I have configured swc-loader as follows:
{
test: /\.tsx?$/,
exclude: /\/node_modules\//,
use: [
{
loader: 'swc-loader',
options: {
jsc: {
externalHelpers: true,
parser: {
dynamicImport: true,
syntax: 'typescript',
},
transform: {
react: {
pragma: 'SnabbdomPragma.createElement',
},
},
},
},
},
],
},
Notice the dynamicImport: true
. Yet running webpack yields an error where I use my dynamic import:
error: import(...) expressions requires `jsc.parser.dynamicImport` to be true
--> /«redacted»/components.ts:21:17
|
21 | return (await import(/* webpackChunkName: "accordion" */ 'components/accordion/Tc.Module.Accordion')).default;
| ^^^^^^
Any other location I need to configure dynamicImport: true
?
If the config supplied to swc-loader is invalid, instead of running with defaults swc should warn the operator and halt compilation.
Do swc-loader not support sourcemap? i Couldn't find any docs of it in the repo.
Would really appreciate an example of enabling full sourcemaps in Webpack.
The following is my configuration.
Thank you!
webpack.js
{
test: /\.tsx?$/,
exclude: /node_modules/,
loader: 'swc-loader',
options: {
sourceMap: true,
}
}
.swcrc
{
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": true,
"decorators": true,
"dynamicImport": true
},
"target": "es2016"
}
}
Unable to pass custom options via swc-loader. (see below).
{
loader: require.resolve("swc-loader"),
options: {
jsc: {
baseUrl: "src",
paths: {
"@services/*": ["services/*"],
"@i18n": ["i18n"],
},
},
},
}
baseUrl
via swc-loader
baseUrl
with webpack's swc-loader
https://github.com/cheuksing/swc-loader-issue-demo
yarn install
README.md
https://www.npmjs.com/package/swc-loader
npm i --save-dev swc swc-loader webpack
in github repo
npm i --save-dev @swc/core swc-loader webpack
When I normally use SWC I call my config .swcrc.json to keep it consistent with tons of other similar configs and so that my IDE can automatically style the JSON, not being able to use .json is a pain.
When normally running swc I use --config-file .swcrc.json
to specify the config, which works fine on most projects. However when using it with swc-loader and webpack, it seems that the config is completely ignored and instead defaults are used. However when calling it ".swcrc" only it seems to work, but I want it to be .json otherwise editing it in IDE looks ugly.
I also don't want to have to duplicate all the configuration to webpack, it's already in .swcrc.json, there shouldn't be any reason to duplicate it in there. Instead swc-loader should be able to read the existing config.
It would be nice if I could use swc-loader and keep my config named what I want it to be named.
swc has support for the plugin(https://swc.rs/docs/usage-plugin)
I'm looking into moving a hobby pet project from Babel to SWC.
My configuration is:
c:\dev\main-app
c:\dev\util
In order to access the utilities repo code as if it was a node_module
, I did:
cd c:\dev
cd util
npm link
cd ../main-app
npm link util
It has created a "symlink" c:/dev/main-app/node_modules/util
→ c:/dev/util
.
Next, I run the app and it says something like:
ERROR in ../util/aaa/bbb.js
Module not found: Error: Can't resolve 'regenerator-runtime' in 'c:\dev\util\aaa'
resolve 'regenerator-runtime' in 'c:\dev\util\aaa'
Parsed request is a module
using description file: `c:\dev\util\package.json` (relative path: `./aaa`)
Field 'browser' doesn't contain a valid alias configuration
resolve as module
`c:\dev\util\aaa\node_modules` doesn't exist or is not a directory
looking for modules in `c:\dev\util\node_modules`
single file module
using description file: `c:\dev\util\package.json` (relative path: `./node_modules/regenerator-runtime`)
no extension
Field 'browser' doesn't contain a valid alias configuration
`c:\dev\util\node_modules\regenerator-runtime` doesn't exist
.js
Field 'browser' doesn't contain a valid alias configuration
`c:\dev\util\node_modules\regenerator-runtime.js` doesn't exist
.json
Field 'browser' doesn't contain a valid alias configuration
`c:\dev\util\node_modules\regenerator-runtime.json` doesn't exist
.wasm
Field 'browser' doesn't contain a valid alias configuration
`c:\dev\util\node_modules\regenerator-runtime.wasm` doesn't exist
`c:\dev\util\node_modules\regenerator-runtime` doesn't exist
`c:\dev\node_modules` doesn't exist or is not a directory
`c:\node_modules` doesn't exist or is not a directory
At the same time: c:\dev\main-app\node_modules\regenerator-runtime
package is installed and exists.
Looks as if SWC ignored the original (main-app
) folder when resolving node_modules
in a symlinked sibling repo folder.
The question is:
Let's cache these files! A fast compiler is not useful if there's no caching.
I wrap @swc/core
in my own package, so that I can maintain a single version in my monorepo.
So I would like to be able to use this in swc-loader
instead of it use it's peer dep.
webpack.config.js
module.exports = {
name: "SWC",
mode: "production",
entry: "./test.js",
output: {
filename: "swc-out.js",
},
module: {
rules: [
{
test: /\.[jt]sx?$/i,
use: [
{
loader: require.resolve("swc-loader"),
options: {
jsc: {
parser: {
syntax: "ecmascript",
},
target: "es2017",
},
module: {
type: "commonjs",
},
},
},
],
},
],
},
};
test.js
import("./data.json").then(console.log);
data.json
"foo"
Run:
yarn webpack
node ./dist/swc-out.js
Output:
{ '0': 'f', '1': 'o', '2': 'o', default: 'foo' }
As reference, here's Babel's equivalent config:
webpack.config.js
module.exports = {
name: "Babel",
mode: "production",
entry: "./test.js",
output: {
filename: "babel-out.js",
},
module: {
rules: [
{
test: /\.[jt]sx?$/i,
use: [
{
loader: require.resolve("babel-loader"),
options: {
presets: [
[
require.resolve("@babel/preset-env"),
{
targets: {
node: "current",
},
},
],
],
plugins: [require.resolve("babel-plugin-dynamic-import-node")],
},
},
],
},
],
},
};
Output:
{ default: 'foo' }
Env:
All code uploaded here: https://github.com/mtgto/example-swc-named-import-error
This code generates runtime error: Uncaught TypeError: c is not a function
.
I check what causes this error:
commonjs
, it does not cause an error.
es6
, still cause same error.import React from "react"; React.useState(0);
does not causes an error.import { render } from "react-dom";
import React, { useState } from "react";
const App = () => {
const [count, setCount] = useState(0); // causes runtime error
//const [count, setCount] = React.useState(0); // It does not cause an error
return (
<div>Hello, world!</div>
);
};
render(<App />, document.getElementById("root"));
// Generated using webpack-cli https://github.com/webpack/webpack-cli
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const isProduction = process.env.NODE_ENV == "production";
const config = {
entry: "./src/index.jsx",
output: {
path: path.resolve(__dirname, "dist"),
},
devServer: {
open: true,
host: "localhost",
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
}),
],
module: {
rules: [
{
test: /\.(jsx)$/i,
exclude: ["/node_modules/"],
use: {
loader: "swc-loader",
options: {
jsc: {
// If set "es6" or undefined to module.type, it causes a runtime error. (`Uncaught TypeError: c is not a function`)
// If set "commonjs" to module.type, it does not causes an error.
/*
module: {
type: "commonjs",
},
*/
parser: {
syntax: "ecmascript",
jsx: true,
},
transform: {
react: {
runtime: "classic",
},
},
minify: {
compress: {
toplevel: true,
},
mangle: {
toplevel: false,
keepClassNames: true,
keepFnNames: true,
keepPrivateProps: true,
}
}
},
},
},
},
],
},
resolve: {
extensions: [".tsx", ".ts", ".jsx", ".js"],
},
};
module.exports = () => {
if (isProduction) {
config.mode = "production";
} else {
config.mode = "development";
}
return config;
};
Firefox DevTools:
Pretty printed js (generated by firefox devtools):
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react-dom */ "./node_modules/react-dom/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
function _arrayLikeToArray(a, b) {
(null == b || b > a.length) && (b = a.length);
for(var c = 0, d = new Array(b); c < b; c++)d[c] = a[c];
return d;
}
var d = undefined;
(0,react_dom__WEBPACK_IMPORTED_MODULE_0__.render)(react__WEBPACK_IMPORTED_MODULE_1__.createElement(function() {
var a, c, f = (c = 2, function(a) {
if (Array.isArray(a)) return a;
}(a = c(0)) || function(a, c) { // ← "Uncaught TypeError: c is not a function"
var d, e, f = null == a ? null : "undefined" != typeof Symbol && a[Symbol.iterator] || a["@@iterator"];
if (null != f) {
var g = [], h = !0, i = !1;
try {
for(f = f.call(a); !(h = (d = f.next()).done) && (g.push(d.value), !c || g.length !== c); h = !0);
} catch (j) {
i = !0, e = j;
} finally{
try {
h || null == f.return || f.return();
} finally{
if (i) throw e;
}
}
return g;
}
}(a, c) || function(a, b) {
if (a) {
if ("string" == typeof a) return _arrayLikeToArray(a, b);
var c = Object.prototype.toString.call(a).slice(8, -1);
if ("Object" === c && a.constructor && (c = a.constructor.name), "Map" === c || "Set" === c) return Array.from(c);
if ("Arguments" === c || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(c)) return _arrayLikeToArray(a, b);
}
}(a, c) || function() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}());
return f[0], f[1], react__WEBPACK_IMPORTED_MODULE_1__.createElement("div", {
__source: {
fileName: "/Users/user/work/js/example-react-swc/src/index.jsx",
lineNumber: 9,
columnNumber: 5
},
__self: d
}, "Hello, world!");
}, {
__source: {
fileName: "/Users/user/work/js/example-react-swc/src/index.jsx",
lineNumber: 13,
columnNumber: 8
},
__self: undefined
}), document.getElementById("root"));
//# sourceURL=webpack://my-webpack-project/./src/index.jsx?
My build works perfectly, except that when I load this one plugin, bundle-stats-webpack-plugin, it starts failing.
webpack.config.js
new BundleStatsWebpackPlugin({
compare: true || false, // both give error
baseline: true || false, // both give error
html: true,
json: true,
})
The error I get when compiling (I compiled with the sync: true
option to have a prettier error message)
ERROR in ./index.js
Module build failed (from ../node_modules/swc-loader/src/index.js):
SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at Object.<anonymous> (/Users/francisco/Projects/manager-ui/node_modules/swc-loader/src/index.js:83:37)
Disabling the parseMap
option fixes this error. The documentation is not very clear on what the parseMap option does, just says to enable it to use swc with babel. I have some babel plugins so I guess I need it?
I want to know if this error might be something of swc, or it's a problem in that particular webpack plugin.
Help is welcome, thanks!
As per: https://swc.rs/docs/configuring-swc/#multiple-entries
We've been trying to use the following swc configuration options:
[
{
"test": ".tsx?$",
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": true,
"decorators": false,
"dynamicImport": true
},
"transform": {
"react": {
"pragma": "React.createElement",
"pragmaFrag": "React.Fragment",
"throwIfNamespace": true,
"development": false,
"useBuiltins": false
}
},
"target": "es5"
}
},
{
"test": ".jsx?$",
"jsc": {
"parser": {
"syntax": "ecmascript",
"jsx": true,
"decorators": false,
"dynamicImport": true
},
"transform": {
"react": {
"pragma": "React.createElement",
"pragmaFrag": "React.Fragment",
"throwIfNamespace": true,
"development": false,
"useBuiltins": false
}
},
"target": "es5"
}
}
]
We've tried adding this to a .swrc
file in the app folder for the app being build and in the root of our Nx monorepo (same folder as our webpack.config.js
). Not sure if it is picked up correctly. Then when we tried setting these options directly in the webpack rule with the loader:
const options = [
{
"test": ".tsx?$",
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": true
},
"transform": {
"react": {
"pragma": "React.createElement",
"pragmaFrag": "React.Fragment",
"throwIfNamespace": true,
"development": false,
"useBuiltins": false
}
},
"target": "es5"
}
},
{
"test": ".jsx?$",
"jsc": {
"parser": {
"syntax": "ecmascript",
"jsx": true
},
"transform": {
"react": {
"pragma": "React.createElement",
"pragmaFrag": "React.Fragment",
"throwIfNamespace": true,
"development": false,
"useBuiltins": false
}
},
"target": "es5"
}
}
]
module.exports = {
test: /\.([jt])sx?$/ ,
exclude: /node_modules/,
use: {
// `.swcrc` in the root can be used to configure swc
loader: require.resolve('swc-loader'),
options
}
}
We get the following error:
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.module.rules[1].use should be one of these:
non-empty string | function | object { ident?, loader?, options?, query? } | function | [non-empty string | function | object { ident?, loader?, options?, query? }]
-> Modifiers applied to the module when rule is matched
Details:
* configuration.module.rules[1].use.options should be an object.
* configuration.module.rules[1].use.options should be a string.
* configuration.module.rules[1].use.options should be one of these:
object | string
* configuration.module.rules[1].use.options should be one of these:
object | string
-> Loader options
Complaining that options must be an object or string. What should we do?
The Webpack rule for swc-loader
when we print it:
{
test: /\.([jt])sx?$/,
exclude: /node_modules/,
use: {
loader: '/Users/kristianmandrup/repos/hogarth/lab-experiments/zonza5-nx/node_modules/swc-loader/src/index.js'
}
}
We need SWC to transpile ts and tsx files as typescript files and js and jsx files as ecmascript files. We are currently transitioning from Javascript to Typescript and have a mix.
ERROR in /Users/kristianmandrup/repos/hogarth/lab-experiments/zonza5-nx/node_modules/zonza5-lib-form-widgets/src/js/UpdateCollectionForm/CreateCollectionForm.jsx 9:4
Module parse failed: Unexpected token (9:4)
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
| errorMessage, onToggleMode, onInputChange, required, label,
| }) => (
> <div className="createCollectionForm">
| <div className="form-group row collection-form">
| <label
Installed Versions
{
"@swc/core": "^1.2.133",
"@swc/jest": "^0.2.17",
"swc-loader": "^0.1.15"
}
The output of swc-loader
is different between these two configurations:
webpack.config.ts (partial)
{
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
use: [ isProduction ? 'babel-loader' : 'swc-loader'],
exclude
},
]
}
}
.browserslistrc
query1
query2
webpack.config.ts (partial)
{
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
use: [
isProduction
? 'babel-loader'
: {
loader: 'swc-loader',
options: {
// swc-loader doesn't seem to automatically detect .browserslistrc
env: {
targets: 'query1, query2'
},
},
},
],
exclude,
},
]
}
}
Option 1 results in es2015 output whereas option 2 uses the browserslist query correctly and results in the expected output.
As a side question, would @swc/jest
also have the same issue?
Thanks!
Over the past week, swc-loader
has begun intermittently throwing errors, and failing to build:
webpack:pid=857 Module build failed (from ../../node_modules/swc-loader/src/index.js):
webpack:pid=857 Error:
webpack:pid=857 x Expected '>', got 'value'
webpack:pid=857 ,-[/app/packages/src/Accordion/index.tsx:80:5]
webpack:pid=857 80 | <AccordionContext.Provider value={contextValue}>
webpack:pid=857 : ^^^^^
webpack:pid=857 `----
This happens to all React components.
Loader config:
{
test: /\.(tsx|mjs|ts)?$/,
exclude: /(node_modules)/,
use: [
{
loader: "swc-loader",
options: {
jsc: {
parser: {
syntax: "typescript"
}
}
}
}
]
}
Versions:
{
"@swc/cli": "^0.1.57",
"@swc/core": "^1.2.171",
"@swc/jest": "^0.2.20",
"swc-loader": "^0.2.0"
}
The weird thing is, one day it will work fine, but the next it starts breaking again with no changes.
Troubleshooting tried:
node_modules
@swc/core
and @swc/cli
to their latest versionsWorking on a team of 200 and successfully migrated from Babel to SWC with 2x speed boost. Absolutely loving SWC 🚀
We're looking to support internationalization using the fbt library. They seem to be tightly coupled with Babel.
Based on these issues: facebook/fbt#392, facebook/fbt#349 it seems like they've punted it to the OS community.
My question is two fold:
Hello,
I believe because of the new way 0.1.16
accesses the options object, apps using Webpack 4 will break.
My app uses Webpack 4 and until I pinned swc-loader
to 0.1.15
, the build
task kept returning this.getOptions is not a function
. So swc-loader
is receiving the Webpack object just fine, but the jump from 4 to 5 broke this operation.
Is re-adding loader-utils
a dealer-breaker? This is my first time getting involved in this repo, so I'm not sure what the tradeoffs are.
Hi, just upgraded my nextjs project to the latest versions yarn upgrade --latest
and got this error:
./utils/parseMarkdown.js
Module parse failed: Optional chaining cannot appear in left-hand side (23:74)
File was processed with these loaders:
* ./node_modules/next/dist/build/webpack/loaders/next-swc-loader.js
You may need an additional loader to handle the result of these loaders.
| const source = section.answer;
| const mdxSource = await serialize(source);
> if (parsedPage.faq.data?.attributes.sections?.length > 0) parsedPage.faq.data?.attributes.sections[index].answer = mdxSource;
| }
| }
I am not sure, which package caused the error.
I assume the error came from next-mdx-remote, but it seems to be a problem with the loader.
If its not, I will create another ticket their.
package.json
{
"private": true,
"license": "Unlicense",
"scripts": {
"dev": "next dev",
"build": "next build",
"postbuild": "next-sitemap",
"start": "next start",
"deploy": "cd strapi; yarn; yarn upgrade; git add . ; git commit -m 'Update strapi'; git push heroku HEAD:main",
"dumpdb": "scripts/dumpdb.sh"
},
"dependencies": {
"@algolia/autocomplete-js": "^1.5.1",
"@algolia/autocomplete-plugin-query-suggestions": "^1.5.1",
"@algolia/autocomplete-plugin-recent-searches": "^1.5.1",
"@phntms/next-gtm": "^0.1.0",
"@tailwindcss/forms": "^0.4.0",
"algoliasearch": "^4.12.0",
"emailjs-com": "^3.2.0",
"framer-motion": "^5.6.0",
"idb-keyval": "^6.1.0",
"memory-cache": "^0.2.0",
"next": "^12.0.8",
"next-mdx-remote": "3.0.8",
"next-pwa": "^5.3.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-facebook-pixel": "^1.0.4",
"react-instantsearch-dom": "^6.19.0",
"react-intersection-observer": "^8.33.0",
"react-lazy-hydration": "^0.1.0",
"react-responsive": "^9.0.0-beta.4",
"react-youtube": "^7.14.0",
"tailwind-scrollbar": "^1.3.1"
},
"devDependencies": {
"autoprefixer": "^10.4.2",
"base-64": "^1.0.0",
"eslint": "8.6.0",
"eslint-config-next": "12.0.8",
"next-sitemap": "^1.9.9",
"postcss": "^8.4.5",
"sharp": "^0.29.1",
"tailwindcss": "^3.0.13"
}
}
'swc-loader' is fast and great. However, if we pass inputSourceMap: true
from loader options, in doesn't work as babel-loader do.
in the source code: the inputSourceMap set as the one from last loader, while babel-loader
from the source code will use it from loader option if no inputSourceMap pass from last loader.
Hi, currently I want to replace babel with SWC for speeding up my project. I change my babel-loader to swc-loader, it make speed faster, but it also makes my bundle size bigger ( increase from 132MB to 174MB ), I want to ask is this behavior is normal or maybe there are somthing i can configure to make my bundle size smaller , thank ~
my babelrc config :
my webpack loader config:
bundle size change :
Hey,
swc looks promising. however, I tried to setup one legacy project with webpack using swc-loader and I have the follwing error when I try to run the project
Failed to compile.
./src/main.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: .inputSourceMap must be a boolean, object, or undefined
at assertInputSourceMap (/code/sample/node_modules/@babel/core/lib/config/validation/option-assertions.js:124:11)
at /code/sample/node_modules/@babel/core/lib/config/validation/options.js:118:5
at Array.forEach (<anonymous>)
at validateNested (/code/sample/node_modules/@babel/core/lib/config/validation/options.js:94:21)
at validate (/code/sample/node_modules/@babel/core/lib/config/validation/options.js:85:10)
at loadPrivatePartialConfig (/code/sample/node_modules/@babel/core/lib/config/partial.js:80:50)
at loadPrivatePartialConfig.next (<anonymous>)
at /code/sample/node_modules/@babel/core/lib/config/partial.js:149:25
at Generator.next (<anonymous>)
at step (/code/sample/node_modules/gensync/index.js:261:32)
at evaluateAsync (/code/sample/node_modules/gensync/index.js:291:5)
at /code/sample/node_modules/gensync/index.js:93:9
at new Promise (<anonymous>)
at async (/code/sample/node_modules/gensync/index.js:92:14)
at Object.<anonymous> (/code/sample/node_modules/babel-loader/lib/index.js:155:26)
at Generator.next (<anonymous>)
I only updated my vue.config.js file like and it starts to load quickly but fail at the end with the error above:
configureWebpack: {
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: "swc-loader",
},
]
},
},
},
I found on the internet that this option in webpack seems to allow load the entire project, but it is slow to load, so I guess It falls back on babel to perform this operation instead of swc
devtool: "eval-cheap-source-map"
I tried this on two projects and tried to update babel dependencies as well. I got this error in both.
Any idea about what is missing, what is going on ?
I am using yarn pnp
, so I cannot use the plugin provided by SWC.
So, I need to use babel-plugin-styled-components
using babel-loader
.
Can I use it with swc-loader
? I think I'm writing the webpack config wrong or it's not working. I think it would be helpful if you write just one webpack config example.
Below is the library I am using.
webpack5
typescript
(^4.4.3)
react17
babel-loader
@babel/core
@babel/preset-env
@babel/preset-react ``@babel/preset-typescript
@babel/runtime
babel-plugin-styled-components
Use config { mode: 'usage' } and the corejs path was not found
"@swc/core": "1.3.41",
"@swc/helpers": "0.4.14",
"swc-loader": "0.2.3"
{
test: /\.(js|jsx)$/,
include: [/(src)/, /(node_modules(\/|\\)@seeyon)/],
use: [
{
loader: 'swc-loader',
options: {
"jsc": {
"parser": {
"syntax": "ecmascript",
"jsx": true,
},
},
"isModule": true,
"env": {
"targets": "Chrome >= 65",
mode: 'usage',
"coreJs": '3.26.1'
}
},
},
],
},
Hi, we are trying to convert our project from using ts-loader to swc-loader.
After installing the node modules and setting up loader: 'swc-loader'
in our webpack files, I'm seeing the below errors occurring.
Terminal error when running docker-compose up --build
:
ERROR in ./src/client/pages/main/index.tsx
Module build failed (from ./node_modules/swc-loader/src/index.js):
Error: Bindings not found.
at Compiler.<anonymous> (/opt/app/node_modules/@swc/core/index.js:224:19)
at Generator.next (<anonymous>)
at /opt/app/node_modules/@swc/core/index.js:34:71
at new Promise (<anonymous>)
at __awaiter (/opt/app/node_modules/@swc/core/index.js:30:12)
at Compiler.transform (/opt/app/node_modules/@swc/core/index.js:201:16)
at Object.transform (/opt/app/node_modules/@swc/core/index.js:343:21)
at Object.<anonymous> (/opt/app/node_modules/swc-loader/src/index.js:86:21)
Terminal error when running npm run build
:
ERROR in ./src/client/pages/main/index.tsx
Module build failed (from ./node_modules/swc-loader/src/index.js):
Error: unknown field `onlyCompileBundledFiles` at line 1 column 350
Added to package.json and installed:
"@swc/cli": "^0.1.57",
"@swc/core": "^1.2.218",
"[swc-loader](https://npmjs.com/package/swc-loader)": "[^0.2.3](https://npmjs.com/package/swc-loader)",
Example webpack config:
module.exports = {
mode: constants.IS_DEVELOPMENT ? 'development' : 'production',
devtool: constants.IS_DEVELOPMENT ? 'inline-source-map' : 'source-map',
target: 'web',
devServer: {
client: {
logging: 'verbose',
overlay: false,
webSocketURL: {
hostname: '0.0.0.0',
pathname: '/ws',
port: constants.PUBLIC_PORT,
},
},
compress: true,
devMiddleware: {
publicPath: constants.PUBLIC_PATH,
},
headers: {
'Access-Control-Allow-Origin': '*',
},
host: config.get('server.hostname'),
hot: true,
port: constants.PUBLIC_PORT,
static: {
directory: constants.STATIC_PATH,
publicPath: constants.PUBLIC_PATH,
watch: true,
},
},
entry: {
main: [
'./src/client/pages/main/index.tsx',
]
},
externals: {
newrelic: 'newrelic',
config: '__MAIN_CONFIG__',
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: [/node_modules/, /__tests__/],
use: [
{
loader: 'swc-loader',
},
],
}, {
test: /\.(c|le)ss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
importLoaders: 1,
sourceMap: true,
url: false,
},
},
'postcss-loader',
{
loader: 'less-loader',
options: {
lessOptions: {
paths: [path.resolve(__dirname, 'node_modules/@vp/visage/src/tokens/less')],
plugins: [
new CleanCSSPlugin({ advanced: true }),
],
},
sourceMap: true,
},
},
].filter(Boolean),
},
],
},
optimization: {
minimizer: [
new TerserJSPlugin({
parallel: 2,
}),
new CssMinimizerPlugin({
parallel: true,
minimizerOptions: {
preset: [
'default',
{
discardComments: { removeAll: true },
},
],
},
}),
],
runtimeChunk: 'single',
sideEffects: true,
splitChunks: {
cacheGroups: {
mainstyles: {
name: 'main-styles',
type: 'css/mini-extract',
chunks: (chunk) => chunk.name === 'main',
enforce: true,
},
mainVendor: {
test: /node_modules/,
chunks: (chunk) => chunk.name === 'main',
name: 'main-vendor',
priority: 10,
enforce: true,
}
},
},
},
output: {
filename: constants.IS_DEVELOPMENT ? '[name].js' : '[name].[contenthash].js',
path: constants.STATIC_PATH,
publicPath: constants.PUBLIC_PATH,
},
plugins: [
new CopyPlugin({
patterns: [
{ from: path.resolve('assets/images'), to: path.resolve('dist/static/images') },
{ from: path.resolve('assets/i18n'), to: path.resolve('dist/static/i18n') },
{ from: path.resolve('assets/json'), to: path.resolve('dist/static/json') },
],
}),
new MiniCssExtractPlugin({
filename: constants.IS_DEVELOPMENT ? '[name].css' : '[name].[contenthash].css',
chunkFilename: constants.IS_DEVELOPMENT ? '[name]-[id].css' : '[name]-[id].[contenthash].css',
}),
new WebpackAssetsManifest({
entrypoints: true,
publicPath: constants.PUBLIC_PATH,
}),
new WebpackCleanPlugin(),
new webpack.DefinePlugin({
// TODO remove this
'process.env.IS_CLIENT': JSON.stringify(true),
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
PUBLIC_PATH: JSON.stringify(constants.PUBLIC_PATH),
}),
constants.IS_DEVELOPMENT ? new webpack.HotModuleReplacementPlugin() : null,
constants.IS_DEVELOPMENT ? new ReactRefreshWebpackPlugin() : null,
constants.IS_DEVELOPMENT ? new DashboardPlugin() : null,
constants.IS_DEVELOPMENT ? new DuplicatesPlugin() : null,
constants.IS_DEVELOPMENT ? null : new webpack.ids.HashedModuleIdsPlugin(),
].filter(Boolean),
resolve: {
alias: {
static: constants.STATIC_PATH,
},
fallback: {
crypto: false,
http: false,
https: false,
util: false,
},
extensions: ['.tsx', '.ts', '.js'],
plugins: [new TsconfigPathsPlugin()],
},
};
.swrc file added
{
"$schema": "https://json.schemastore.org/swcrc",
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": true,
"decorators": true,
"dynamicImport": false
},
"transform": {
"react": {
"refresh": true
}
},
"target": "es5",
"loose": false,
"externalHelpers": false
},
"minify": false
}
Other information:
Source maps are not present even if they are enabled (both TS & JS files)
Could not load content for webpack:///../src/messages-legacy/MessageService.ts (HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME)
const config = {
entry: {
'app.start': [
!isProd && !disableReactFastRefresh && 'webpack-hot-middleware/client',
'core-js/stable',
'regenerator-runtime/runtime',
'webcrypto-shim',
'url-polyfill',
'src/app/startup/appGlobal',
'src/app/startup/app.start.js',
],
// other entrypoints
},
output: {
path: path.join(publicDirPath, 'buildTemp/'),
publicPath: '/buildTemp/',
filename: '[name].js',
},
mode: 'development',
devtool: 'inline-cheap-source-map',
loaders: [
{
test: /\.m?jsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'swc-loader',
options: {
"test": ".jsx?$",
"sourceMap": true,
"jsc": {
"parser": {
"syntax": "ecmascript",
"jsx": true,
"decorators": false,
"dynamicImport": true
},
"transform": {
"react": {
"pragma": "React.createElement",
"pragmaFrag": "React.Fragment",
"throwIfNamespace": true,
"development": false,
"useBuiltins": false
}
},
"target": "es2015"
},
"module": {
"type": "commonjs",
"strict": false,
"strictMode": true,
"lazy": false,
"noInterop": false
}
},
},
],
},
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'swc-loader',
options: {
"test": ".tsx?$",
"sourceMap": true,
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": true,
"decorators": false,
"dynamicImport": true
},
"transform": {
"react": {
"pragma": "React.createElement",
"pragmaFrag": "React.Fragment",
"throwIfNamespace": true,
"development": false,
"useBuiltins": false
}
},
"target": "es5"
},
"module": {
"type": "commonjs",
"strict": false,
"strictMode": true,
"lazy": false,
"noInterop": false
}
},
},
],
},
]
}
inline-cheap-source-map, cheap-source-map - This will show transformed javascript files
cheap-module-source-map, inline-cheap-module-source-map, source-map, etc. - This will throw mentioned error when i want to original display file (404)
With babel-loader, source maps works
I'd like to read what the breaking changes are between v0.1
and v0.2
I'm getting an error when trying to follow the example with webpack:
> ./node_modules/.bin/webpack
Hash: f728d32ddf1c4679aa5c
Version: webpack 4.29.0
Time: 102ms
Built at: 01/21/2019 5:42:22 PM
Asset Size Chunks Chunk Names
main.js 3.99 KiB main [emitted] main
Entrypoint main = main.js
[./src/index.js] 226 bytes {main} [built] [failed] [1 error]
ERROR in ./src/index.js
Module build failed (from ./node_modules/swc-loader/src/index.js):
ReferenceError: filename is not defined
at Object.<anonymous> (/Users/ivan/dev/swc-static/node_modules/swc-loader/src/index.js:26:13)
The full repo to reproduce the error is available here: https://github.com/ivanoats/swc-webpack-react-demo
I'm excited to start using this, looks like a great project.
https://github.com/jeremy-coleman/swc-react-hmr
same as the one here, just using typescript and latest hmr setup - works
feel free to copy and paste it into the example dir if you want or want to use the hmr bit, probably most people have problems setting that up
Im using an inline style-loader call in a js file
const lessVar = require(`!!style-loader?{"esModule":false}!css-loader?{"esModule":false,"modules":"icss"}!less-loader!link.to.lessFile.less`);
and this error is thrown:
Module not found: Error: Can't resolve 'style-loader' in 'link/to/relative/file'
The webpack config for resolving loaders is set correctly so this seems to be a swc-loader issue
Compiling ts with swc is blazingly fast, and its advantage over esbuild is that it supports decorate metadata, which is great.
I hope that swc-loader can support appendTsSuffixTo in the future, just like ts-loader appendTsSuffixTo, so that swc-loader can better support the compilation of .vue files
This is what I do now and it works fine so far. But I'm not sure if there are other problems with this。
// webpack.config.ts
// ...... other rules
{
test: /\.ts$/i,
exclude: ["/node_modules/"],
use: [
'swc-loader',
resolve(__dirname, 'custom-loader')
],
},
// ...... other rules
// custom-loader.js
module.exports = function (content, sourceMap, meta) {
if (sourceMap && this.resourcePath && this.resourcePath.endsWith(".vue")) {
this.resourcePath += ".ts"
}
return content
}
This is what I do now and it works fine so far. But I'm not sure if there are other problems with this. If anyone can tell me how to add an option to swc-loader to do something similar, maybe I can submit a pull request
I have an ejected CRA with a custom webpack loader. I use swc-loader
instead of babel-loader
for faster compile time. Actually, I add @walletconnect/web3-provider
into my app. I got an error to include { util: require.resolve('util/') }
into resolve.fallback
webpack configuration. After that error was fixed, I got the error again like this
ERROR in ./node_modules/util/util.js
Module build failed (from ./node_modules/swc-loader/src/index.js):
Error:
× the name `fn` is defined multiple times
╭─[/media/data/SIDE_PROJECTS/webpack-react-ts-inversify-web-worker/node_modules/util/util.js:617:5]
617 │ var fn = original[kCustomPromisifiedSymbol];
· ─┬
· ╰── previous definition of `fn` here
618 │ if (typeof fn !== 'function') {
619 │ throw new TypeError('The "util.promisify.custom" argument must be of type Function');
620 │ }
621 │ Object.defineProperty(fn, kCustomPromisifiedSymbol, {
622 │ value: fn, enumerable: false, writable: false, configurable: true
623 │ });
624 │ return fn;
625 │ }
626 │
627 │ function fn() {
· ─┬
· ╰── `fn` redefined here
╰────
I request to refactor fn
variable/function definition, but I have a comment like this from its member:
browserify/node-util#75 (comment)
Maybe, is swc-loader
(or @swc/core
) has a problem incorrectly defaulting CJS code to strict mode?
It seems like I'm constantly receiving errors while building using webpack
ERROR in ./server/server.ts
Module build failed (from /home/yuval/code/Moneytor/Moneytor/node_modules/swc-loader/src/index.js):
TypeError: this.getOptions is not a function
at Object.<anonymous> (/home/yuval/code/Moneytor/Moneytor/node_modules/swc-loader/src/index.js:9:34)
It is worth mentioning I'm trying to bundle the backend application and I don't use swc-pack
since it doesn't have all the required options I need
Currently, I'm on WSLv2 on Windows 11
Node 16.14.2
Webpack 5.72.0 (But I also tried 4.46.0)
const CopyWebpackPlugin = require('copy-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
const tsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const path = require('path');
module.exports = (env, argv) => ({
mode: argv.mode === 'production' ? 'production' : 'development',
target: 'node',
node: {
__dirname: false,
__filename: false,
},
externals: [
nodeExternals({
modulesFromFile: true,
}),
],
devtool: 'inline-source-map',
entry: {
server: './server/server.ts',
},
module: {
rules: [
{
test: /\.ts$/,
use: {loader: 'swc-loader'},
include: [path.resolve(__dirname, 'server')],
exclude: [path.resolve(__dirname, 'dist'), /node_modules/],
},
{
test: /\.(png|jp(e*)g|svg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'images/[hash]-[name].[ext]',
},
},
],
exclude: [path.resolve(__dirname, 'dist'), /node_modules/],
},
],
},
// Webpack tries these extensions for you if you omit the extension like "import './file'"
resolve: {
plugins: [new tsconfigPathsPlugin()],
extensions: ['.tsx', '.ts', '.jsx', '.js'],
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, './dist'), // Compile into a folder called "dist"
},
plugins: [...plugins],
});
When using swc I set module type to nodenext
, however when I use the exact same setup with swc-loader, it seems that suddenly I can't select that option any more. It breaks with the unknown variant error above and says that I can only use commonjs
, umd
, amd
, systemjs
, es6
, when swc allows you to use nodenext
.
SWC recently added support for nodenext and things like es2022. I believe this issue might be simply because swc-loader is using an old "@swc/core": "^1.2.147"
dependency.
I'm trying to port from babel-loader and ts-loader to swc-loader, but everytime require.context
is called, it returns undefined.
When printing the require
variable, it returns the following module:
function webpackEmptyContext(req) {
var e = new Error("Cannot find module '" + req + "'");
e.code = 'MODULE_NOT_FOUND';
throw e;
}
webpackEmptyContext.keys = () => ([]);
webpackEmptyContext.resolve = webpackEmptyContext;
webpackEmptyContext.id = 5102;
module.exports = webpackEmptyContext;
latest version
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.