Related
I am running a next.js project, as the project grew my imports became harder and harder to read.
Which is why I really love the path aliasing in jsconfig.json. Makes everything so much cleaner.
However, and that's a big however, I used to be able to click on any variable (or import) holding cmd and would be directly taken to the final definition. Same with getting a peek ("Code Peek") into the module/variable that I was importing.
This functionality did not seem to work with aliases. Installing module-resolver helped on the top level. I.e. click-through through is now possible for everything starting with #/Components but not the lower level aliases. Any Idea how to fix that?
Caveats:
I know I should, but I am currently not yet using es-lint,
nor am I explicitly using webpack (I know next.js uses it under the hood)
Plain Javascript (no typescript)
Those tools are surely useful, but I want to keep the additional tooling to a minimum right now.
Configs:
This is my jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"#/Components/*": ["components/*"],
"#/Concepts/*": ["components/Concepts/*"],
...
}
}
}
this is my .babelrc
{
"presets": ["next/babel"],
"plugins": [
["styled-components", { "ssr": true }],
["module-resolver", {
"root": ["."],
"alias": {
"#/Components": "components",
"#/Concepts": "components/Concepts",
...
}
}]
]
}
I am importing like this (both imports work):
Click-through works:
import { Bold } from "#/Components/styles";
Click-through does not work:
import { DefaultMarginSlider, Formula } from "#/Concepts/utils";
for completeness sake here is my package.json
I got it working with the following config settings
jsconfig.json
{
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"allowSyntheticDefaultImports": true,
"baseUrl": "src",
"jsx": "react",
"noImplicitAny": false,
"paths": {
"components/*": [
"./components/*"
],
"utils/*": [
"./utils/*"
],
"UI/*": [
"./UI/*"
],
"assets/*": [
"./assets/*"
]
}
},
"exclude": ["node_modules"]
}
my .eslintec file looks like
{
"env": {
"browser": true,
"es6": true
},
"extends": [
"plugin:import/react",
"airbnb"
],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"settings": {
"import/resolver": {
"alias": {
"map": [
[
"UI",
"./src/UI"
],
[
"components",
"./src/components"
],
[
"assets",
"./src/assets"
]
],
"extensions": [
".js",
".jsx",
".svg",
".png"
]
},
"webpack": {
"config": "config/webpack.config.js"
}
}
},
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 2018,
"sourceType": "module"
},
"parser": "babel-eslint",
"plugins": [
"react",
"react-hooks",
"import",
"resolver-alias"
],
"rules": {}
}
And there are the extra plugins I installed to get it working
eslint-import-resolver-alias
eslint-import-resolver-webpack
eslint-plugin-import
And this is my webpack config to resolve while building
resolve: {
modules: ['node_modules', paths.appNodeModules].concat(
modules.additionalModulePaths || []
),
extensions: paths.moduleFileExtensions
.map(ext => `.${ext}`)
.filter(ext => useTypeScript || !ext.includes('ts')),
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-dom': '#hot-loader/react-dom',
'components': path.resolve(__dirname, '../src/components'),
'assets': path.resolve(__dirname, '../src/assets'),
'UI': path.resolve(__dirname, '../src/UI'),
'utils': path.resolve(__dirname, '../src/utils'),
...(isEnvProductionProfile && {
'react-dom$': 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
}),
...(modules.webpackAliases || {}),
},
plugins: [
PnpWebpackPlugin,
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
For next.js you can skip the above webpack config and eslint-import-resolver-webpack npm package. It will work fine.
I am trying to optimize my webpack bundle size by splitting it into two bundles: webpack-bundle.js, which contains my code, and vendor-bundle.js, which contains node modules and third party libraries. But after I successfully created two bundles, I am getting two errors in the browser regarding both bundles:
Uncaught ReferenceError: exports is not defined at vendor-bundle.self-879f615019647c756dc959f99d735b3a2534b00805364ae6fca0091d1190d62d.js?body=1:1
Uncaught TypeError: Cannot read property 'call' of undefined at I (webpack-bundle.self-78221fc03008c178fe970b69731594f14d651dab84e5cf928beacc805ebde79c.js?body=1:1)
This is my webpack.config.js.
const config = {
"entry": {
"webpack-bundle": "./app/registration",
},
"output": {
filename: "[name].js",
path: pathLib.resolve(__dirname, "../app/assets/webpack"),
},
"module": {
"rules": [
{
"exclude": /node_modules/,
"test": /\.jsx?$/,
"use": {
"loader": "babel-loader",
"options": {
"plugins": [
"#babel/plugin-proposal-class-properties",
["#babel/plugin-proposal-decorators", {"legacy": true}],
"#babel/plugin-proposal-export-namespace-from",
"#babel/plugin-proposal-function-sent",
"#babel/plugin-proposal-json-strings",
"#babel/plugin-proposal-numeric-separator",
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-proposal-throw-expressions",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-syntax-import-meta",
"#babel/plugin-transform-react-jsx"
],
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
}
}
],
},
"plugins": [
new webpack.ProvidePlugin({
"$": "jquery",
"jQuery": "jquery",
"window.jQuery": "jquery"
}),
new UglifyJsPlugin(),
],
"optimization": {
"splitChunks": {
"cacheGroups": {
"vendor": {
"test": /node_modules/,
"chunks": "all",
"name": "vendor-bundle"
}
}
}
},
"resolve": {
"alias": {
"Lib": pathLib.resolve(__dirname, "app/lib/"),
"Shared": pathLib.resolve(__dirname, "app/shared/")
},
"extensions": [".js", ".jsx"]
},
"target": "node"
};
module.exports = config;
This is my .babelrc:
{
"plugins": [
"#babel/plugin-proposal-class-properties",
["#babel/plugin-proposal-decorators", {"legacy": true}],
"#babel/plugin-proposal-export-namespace-from",
"#babel/plugin-proposal-function-sent",
"#babel/plugin-proposal-json-strings",
"#babel/plugin-proposal-numeric-separator",
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-proposal-throw-expressions",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-syntax-import-meta",
"#babel/plugin-transform-react-jsx"
],
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
We use React, Rails, React on Rails, and Slim. To load webpack, I'd add this to my application.slim:
= javascript_include_tag 'vendor-bundle'
= javascript_include_tag 'webpack-bundle'
I want to be able to serve the two bundles I created. Is there anything wrong in the way I configured my webpack and split the bundle? Or should I install something else?
At the bottom of your webpack config, you have your target mode set to node
In node, module and module.exports both exist, but these don’t exist in the browser - this is what’s causing the error
If you remove this line, webpack will assume you’re targeting browsers instead, and will also transform this line for you - your bundles should then run in the browser as expected.
I'm upgrading to Babel v7 from v6 and when I build the project I get the following error:
Syntax error: src\app\layout\components\FooterToolbar.js: Unexpected token
I'm using the following .babelrc configuration
{
"presets": [
["#babel/preset-env", { "useBuiltIns": "usage", "debug": true }],
"#babel/preset-typescript",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-transform-runtime"
]
}
And finally this is my webpack config. I put the pollyfills first and then the index.js file in the entry and the babel-loader as transpiler
entry: ["#babel/polyfill", paths.appIndexJs],
// Process JS with Babel.
{
test: /\.(js|jsx|mjs|ts|tsx)$/,
exclude: /node_modules/,
include: paths.appSrc,
use: [{ loader: 'babel-loader' }],
},
Any advice to solve this issue? Thanks a lot
EDIT: I'm using typescript in this project. This is the tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"moduleResolution": "node",
"esModuleInterop": true,
"isolatedModules": true,
"strict": true,
"noEmit": true,
"allowJs": true,
"resolveJsonModule": true,
"jsx": "react"
},
"include": [
"src"
]
}
Finally got it to work by updating webpack, its plugins and adding the presets and plugins inside the webpack configuration
// Process JS with Babel.
{
test: /\.(js|jsx|mjs|ts|tsx)$/,
exclude: /node_modules/,
include: paths.appSrc,
use: [{
loader: 'babel-loader',
options: {
presets: [
["#babel/preset-env", { modules: "commonjs" }],
"#babel/preset-typescript",
"#babel/preset-react"
],
plugins: [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-transform-runtime"
]
}
}],
},
Thanks for your answers, hopefully this is useful for someone else
In their website, webpack shows plugin usage like this
plugins: [
new webpack.optimize.UglifyJsPlugin(),
new HtmlWebpackPlugin({template: './src/index.html'})
]
I want to use babel plugin transform-async-to-generator, so I added it in babelrc file but I dont know this is enough, should I add it also webpack file ? If so how
I can not be sure if writing plugin in webpack config file required because right now I am getting runtime error and not sure if it works writing only in babelrc file.
my current webpack config file
var path = require('path')
module.exports = {
entry: path.resolve(__dirname, 'partner/index.js'),
output: {
path: path.resolve(__dirname, './dist'),
filename: 'partner_bundle.js'
},
target: 'web',
module: {
rules: [
{
test: /\.js$/, // Check for all js files
loader: 'babel-loader',
query: {
presets: [
'babel-preset-env',
'babel-preset-stage-0'
].map(require.resolve)
},
exclude: /node_modules\/(?!other-module)/
}
]
},
stats: {
colors: true
},
devtool: 'source-map',
resolve: { symlinks: false }
}
babelrc file
{
"presets": [
"env",
"stage-2"
],
"plugins": [
"transform-async-to-generator",
"transform-async-generator-functions",
[
"transform-runtime",
{
"helpers": false,
"polyfill": false,
"regenerator": true
}
]
]
}
Here you can see in my webpack config how I include the babel plugins:
test: /(\.jsx|\.js)$/, // JSX and JS files should be present.
exclude: /(node_modules|bower_components)/,
use: [{
loader: 'babel-loader',
options: {
// Babel must be required like this to be able to use npm-link to link to shared code, see:
// https://stackoverflow.com/questions/34574403/how-to-set-resolve-for-babel-loader-presets/
presets: [
[node_modules + '/#babel/preset-env', {
// Ref: 1) http://2ality.com/2017/02/babel-preset-env.html
// 2) http://caniuse.com/usage-table
// In case it supports the browserlist in package.json, remove this here, see:
// https://github.com/babel/babel-preset-env/issues/149
"targets": {"browsers": ["> 4%", "safari 10", "ie 11", "iOS 9"]},
"modules": false,
"useBuiltIns": 'entry',
// "debug": true
}],
[node_modules + '/#babel/preset-react'],
],
plugins: [
node_modules + '/#babel/plugin-proposal-class-properties',
node_modules + '/#babel/plugin-proposal-object-rest-spread'].map(require.resolve)
}
}]
I have a React project setup and I'm trying to incorporate MobX into it. With that I have to use decorators i.e.
#observable
When I do that though I get the following error:
https://github.com/mobxjs/mobx
Module build failed: SyntaxError: Unexpected token (5:22)
class ListStore {
#observable items = ['Pete', 'John', 'Henry', 'Jeff', 'Bob'];
}
My Webpack config:
module.exports = {
entry: './src/App.js',
output: {
path: __dirname,
filename: 'app.js'
},
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react'],
plugins: ['transform-decorators-legacy']
}
},
{
test: /\.scss?$/,
exclude: /node_modules/,
loaders: ['style', 'css', 'sass']
}]
}
};
My ESLint config:
{
"parserOptions": {
"ecmaVersion": 6,
"ecmaFeatures": {
"jsx": true
},
"sourceType": "module"
},
"env": {
"browser": true,
"node": true,
"es6": false
},
"ecmaFeatures": {
"modules": true
},
"rules": {
"strict": [
2,
"global"
],
"quotes": [
2,
"single"
],
"indent": [
2,
4
],
"eqeqeq": [
2,
"smart"
],
"semi": [
2,
"always"
],
"max-depth": [
2,
4
],
"max-statements": [
2,
15
],
"complexity": [
2,
5
]
}
}
As a note, I'm new to using Webpack as well as utilising ESLint, so this might very well be a newby question. However after doing research online I haven't find anything that's worked. (This includes installing the 'transform-decorators-legacy' Babel plugin).
I think that the issue isn't so much the decorator, but the property initializer syntax. It'll probably fail on this as well:
class ListStore {
items = ['Pete', 'John', 'Henry', 'Jeff', 'Bob']
}
To support those, you can add the transform-class-properties plugin:
$ npm install babel-plugin-transform-class-properties --save
(and update your Webpack config accordingly)
Or use a Babel preset that includes it (stage-2, stage-1 or stage-0).