Not getting Intellisense from a webpack module in VS Code - javascript

I am building a javascript library using NPM and webpack but can't seem to get intellisense to work on my exported module. At the bottom of this post I have included a link to a zip of a small demo project that depicts the problem. Specifically I have a SimulatedClient.js file which imports my module from the dist folder. If you try to use the module it works as intended and has all of the data it should, but you don't get any intellisense/autocomplete in VScode, which makes development a nightmare. How can I get vscode to give valid autocomplete for my module output? Thanks for your help and here is my current webpack setup which is also included in the attached zip:
module.exports = {
target: "web",
entry: { vueStyles: "./src/js/vueStyles.js" },
mode: "development",
devtool: "source-map",
output: {
filename: "[name].js",
path: path.join(__dirname, "dist"),
library: "vueStyles",
libraryTarget: "umd",
globalObject: "this",
umdNamedDefine: true,
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
loader: "css-loader",
options: {
importLoaders: 1,
},
}),
new CleanWebpackPlugin(),
new ProgressBarPlugin({
format: " vueStyles webpack [:bar] " + chalk.green.bold(":percent") + " (:elapsed seconds): :msg",
clear: false,
}),
],
module: {
rules: [
{
test: /\.(sa|s?c)ss$/i,
use: [MiniCssExtractPlugin.loader, "css-loader", "postcss-loader", "sass-loader"],
},
{
test: /\.m?js$/i,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"],
plugins: [
"#babel/plugin-transform-runtime",
"#babel/plugin-proposal-nullish-coalescing-operator",
"#babel/plugin-proposal-optional-chaining",
],
},
},
},
{
test: /\.(svg|ttf|eot|woff2?)$/,
loader: "url-loader?name=[name].[ext]",
},
],
},
};
Test Solution Zip

Related

Preact and react-redux bug with dynamic loading

I'm working with preact, and loading a module dynamically within my code, using webpack code-splitting.
If I load my core bundle using a script tag, everything works perfectly. If I load it dynamically like the code bellow, the bundle breaks:
const script = document.createElement('script');
script.src = 'bundle-location.js';
document.body.appendChild(script);
This is the error I get:
If I add a breakpoint inside the Context.js file, I can see the problem:
In the first case, if using the script tag, then react__WEBPACK_IMPORTED_MODULE_0__ actually contains preact. For some reason that's eluding me, if I load the same script dynamically, the preact object exists, but is missing all of its exports, including the 'default' export.
It's important to note that if I disable code-splitting, then everything works properly.
This is my webpack configuration:
const config = {
mode: getMode(),
resolve: {
alias: {
react: 'preact/compat',
'react-dom': 'preact/compat',
},
extensions: ['.ts', '.tsx', '.js'],
},
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.svg$/,
exclude: /node_modules/,
use: [
'babel-loader',
{
loader: 'react-svg-loader',
query: {
svgo: {
pretty: true,
plugins: [
{
removeStyleElement: true,
},
{
removeViewBox: false,
},
],
},
},
}],
},
],
},
plugins: [
new webpack.DefinePlugin({
PLUGINS_PATH: JSON.stringify(getPluginsPath()),
}),
],
entry: './src/index.ts',
output: {
path: path.resolve(__dirname, './src/dist/bundle/'),
filename: 'bundle.js',
chunkFilename: '[name].js',
publicPath: getPluginsPath(),
},
};
module.exports = config;
Would really appreciate any direction.

React native web storybook react-native-vector-icons problem icon

I'm developing a react native component on storybook, which uses react-native-paper and react-native-vector-icons.
The problem is that I can't see the icons, I tried to follow the guide on react-native-vector-icons, this: webpack
Below is the webpack, but I didn't quite understand how to use the second part of the code suggested in the guide, where and how I should use it.
Can anyone help me out?
webpack:
const path = require('path')
const HTMLWebpackPlugin = require('html-webpack-plugin')
const HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
template: path.resolve(__dirname, './public/index.html'),
filename: 'index.html',
inject: 'body',
})
module.exports = {
entry: path.join(__dirname, 'index.web.js'),
output: {
filename: 'bundle.js',
path: path.join(__dirname, '/build'),
},
resolve: {
alias: {
'react-native$': 'react-native-web',
'#storybook/react-native': '#storybook/react',
'styled-components/native': 'styled-components',
},
},
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
exclude: /node_modules[/\\](?!react-native-vector-icons)/,
use: {
loader: 'babel-loader',
options: {
// Disable reading babel configuration
babelrc: false,
configFile: false,
presets: [
'#babel/preset-env',
'#babel/preset-react',
'#babel/preset-flow',
'#babel/preset-typescript',
{
plugins: ['#babel/plugin-proposal-class-properties', '#babel/plugin-proposal-object-rest-spread'],
},
],
},
},
},
{
test: /\.(jpg|png|woff|woff2|eot|ttf|svg)$/,
loader: 'file-loader',
},
{
test: /\.ttf$/,
loader: 'url-loader', // or directly file-loader
include: path.resolve(__dirname, 'node_modules/react-native-vector-icons'),
},
],
},
plugins: [HTMLWebpackPluginConfig],
devServer: {
historyApiFallback: true,
contentBase: './',
hot: true,
},
}
The reason for your problem could be that your webpack.config.js is located in the folder .storybook.
So you have to change the path for loading the react-native-vector-icons and add ../ before node_modules, because of the folder structure.
...
{
test: /\.ttf$/,
loader: 'url-loader', // or directly file-loader
// add .. to the path for node_modules
include: path.resolve(__dirname, '../node_modules/react-native-vector-icons'),
},
...
An similar issue has been described and solved here: React Native Vector Icons don't load on react-native-web storybook

Webpack: ignore references to svg/ttf files in css

I'm using webpack to export a css file. I'm using file-loader for svg/ttf files but it seems to copy them to the dist folder. Is there a way I can get webpack to just ignore referneces to svg/ttf in my css and leave as is? I've tried ignore-loader but it just replaces the file paths with [Object object].
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
performance: { hints: false },
mode: 'development',
devtool: 'source-map',
entry: ['babel-polyfill', './js/react-components/src/index.js'],
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'js/react-components/dist')
},
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// all options are optional
filename: 'output.css',
chunkFilename: 'chunk[id].css',
ignoreOrder: false, // Enable to remove warnings about conflicting order
}),
],
module: {
rules: [
{
test: /\.(png|svg|jpg|gif|ttf|eot|svg|woff(2)?)(\?[a-z0-9-]+)?$/,
loader: 'file-loader'
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
resolve: {
extensions: [".js", ".jsx"]
},
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [
{ loader: MiniCssExtractPlugin.loader,
options: {},
},
"css-loader"
]
}
]
}
};
I had a similar use case
Use esModule: false to fix the [Object object] in paths.
Also put all the assets in a /static/ folder (source is destination).
{
test: /\.(svg|png|jpe?g|gif)$/i,
loader: 'file-loader',
options: {
outputPath: '../static',
name: '[name].[ext]',
esModule: false
},
},
EDIT: Well that created a loop with npm run watch
I gave up and let the files be copied put the outputPath: './'
I also had to add an exception to CleanWebpackPlugin, or else they
plugins: [
new CleanWebpackPlugin({
cleanAfterEveryBuildPatterns: ['!*.svg']
}), ...

Moving from webpack v1 to v2

I'm trying to migrate my code from webpack v1 to v2 and add in the sass-loader, however I get the error
throw new WebpackOptionsValidationError(webpackOptionsValidationErrors);
I'm very confused as to what the final file is supposed to look like:
let webpack = require('webpack');
let path = require('path');
module.exports = {
devtool: 'eval-source-map',
entry: [
'./src/index'
],
module: {
rules: [
{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"sass-loader" // compiles Sass to CSS
]
}],
test: /\.js?$/,
loader: 'babel-loader',
exclude: /node_modules/
},
resolve: {
extensions: ['.js'],
options: {
enforceExtension: false
}
},
output: {
path: path.join(__dirname, '/dist'),
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './dist',
hot: true,
historyApiFallback: true
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.LoaderOptionsPlugin({
debug: true,
options: {
context: __dirname
}
})
]
};
At the moment the code is a mix of the two versions. I am using webpack version 2.2.1. Thanks.
There are several things you need to change:
Your test: /\.js?$/ and the corresponding loader and exclude should be another object inside the rules array:
module: {
rules: [
{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"sass-loader" // compiles Sass to CSS
]
},
{
test: /\.js?$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
},
resolve.options does not exist, it is just resolve.enforceExtension directly:
resolve: {
extensions: ['.js'],
enforceExtension: false
},
And finally, although it's not an error but just a warning, new webpack.NoErrorsPlugin() is deprecated and has been replaced with:
new webpack.NoEmitOnErrorsPlugin()
Also if you haven't yet, you should have a look at the migration guide from the official docs https://webpack.js.org/guides/migrating/.

Webpack module-type sourcemaps are pointing to 'undefined' file

I'm building an app with multiple widgets. These widgets are fairly big in size, so they are placed in separate sub-directories within the parent directory. The file structure looks something like this:
./
+-- server/
|
+-- client/
|
+-- widget1/
|
+-- widget2/
|
+-- widget3/
|
+-- package.json
+-- webpack.base.config
Each widget is a module completely separated from the other client and widgets, and are developed on their own, with their own development servers, etc.
Now the problem: when setting the webpackConfig.devtool to anything that uses module (ie. cheap-module-source-map), the widget files do not receive the correct source-maps. Instead they receive a filename/line number that looks like: (index):40. (or webpack:///:40 when mousing over) When clicking on said file in chrome, it points me to a file with these contents:
undefined
/** WEBPACK FOOTER **
**
**/
Now the incredibly weird thing about this is that even when building the client app, which brings all the widgets and the client-side code together, only the widget files have these messed up source-maps.
The contents of each widget is simply a bunch of .js and .scss files, with an index.html and development-server.js for development. The client side code is virtually the same, expect for the development files.
This is webpack-1, version 1.13.0.
My webpack.base.config looks like such:
const babelQuery = {
es2015: require.resolve('babel-preset-es2015'),
react: require.resolve('babel-preset-react'),
};
function createQuery(...paths) {
return paths.map(resolvePath => `presets[]=${resolvePath}`).join(',');
}
const fullQuery = createQuery(babelQuery.es2015, babelQuery.react);
module.exports = {
cache: true,
context: __dirname,
debug: true,
devtool: '#cheap-module-source-map',
entry: {},
output: {},
resolve: {
extensions: ['', '.js', '.jsx'],
},
module: {
loaders: [
{
test: /\.js$/,
loader: `babel-loader?cacheDirectory,${createQuery(babelQuery.es2015)}`,
exclude: /node_modules/,
},
{
test: /\.jsx$/,
loader: `react-hot-loader!babel-loader?cacheDirectory,${fullQuery}`,
exclude: /node_modules/,
},
{
test: /\.json$/,
loader: 'json-loader',
},
{
test: /\.scss$/,
loader: 'style-loader' +
'!css-loader?modules&sourceMap&localIdentName=[name]__[local]___[hash:base64:5]' +
'!postcss-loader!sass-loader?outputStyle=expanded&sourceMap',
},
{
test: /\.(png|jpg|gif)$/,
loader: 'file-loader?name=img/[name].[ext]',
},
{
test: /\.(ttf|eot|svg|woff(2)?)(\?v=\d+\.\d+\.\d+)?(\?[a-z0-9]+)?$/,
loader: 'file-loader',
},
{
test: /\.css$/,
loader: 'style-loader!css-loader?modules&localIdentName=[name]__[local]___[hash:base64:5]',
include: /flexboxgrid/,
},
{
test: /\.css$/,
loader: 'style-loader!css-loader',
exclude: /flexboxgrid/,
},
],
},
postcss() {
return [autoprefixer];
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('development'),
},
}),
],
};
The widgets' development servers modify the base config like so: (if it matters)
context: __dirname,
entry: {
bundle: [
'webpack/hot/dev-server',
'webpack-hot-middleware/client',
'./entry.jsx',
],
},
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: `http://localhost:${PORT}/assets/`,
filename: '[name].js',
},
Try eval-source-map or source-map.
It's slower I know, but with a small cost of longer rebuilding time in dev mode it works just fine.
My loader in webpack config looks like this:
{
output: {
pathinfo: true,
path: path.join(__dirname, "build"),
filename: "app.js",
publicPath: "/"
},
entry: [
"webpack-dev-server/client?http://0.0.0.0:3000",
"webpack/hot/only-dev-server",
"babel-polyfill",
"whatwg-fetch",
path.join(__dirname, "./main")
],
devtool: "eval-source-map",
module: {
loaders: [
{
test: /\.jsx?$/,
include: [
path.join(__dirname, "src"),
path.join(__dirname, "node_modules/localforage")
],
loader: "react-hot!babel?cacheDirectory"
},
]
}
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.DefinePlugin({
"process.env": {
"NODE_ENV": "\"development\"",
"BASE_DIR": "\"baseDir\"",
}
})
]
}
and my .babelrc:
{
"presets": ["es2015", "stage-0", "react"],
"plugins": ["transform-decorators-legacy"],
"env": {
"production": {
"presets": ["react-optimize"]
}
}
}

Categories

Resources