How to resolve aliases in Storybook? - reactjs

I have a React/Typescript project with Storybook. Storybook works great, but as soon as I start importing files with aliases, it crashes.
Example:
import Foo from "#components/foo" => crash
import Foo from "../../components/foo" => ok
The app works fine with the aliases. The issue is only related to Storybook.
Here is my storybook config:
module.exports = {
stories: ["../**/stories.tsx"],
webpackFinal: (config) => {
return {
...config,
module: {
...config.module,
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: { loader: "babel-loader" },
},
{ test: /\.css$/, use: ["style-loader", "css-loader"] },
{ test: /\.(png|jpg|gif)$/, use: ["file-loader"] },
{
test: /\.svg$/,
use: [
{
loader: "babel-loader",
},
{
loader: "react-svg-loader",
options: {
jsx: true,
},
},
],
},
],
},
};
},
typescript: {
check: false,
checkOptions: {},
reactDocgen: "react-docgen-typescript",
reactDocgenTypescriptOptions: {
shouldExtractLiteralValuesFromEnum: true,
propFilter: (prop) =>
prop.parent ? !/node_modules/.test(prop.parent.fileName) : true,
},
},
};
My webpack config:
/* eslint-env node */
const path = require("path");
const TerserPlugin = require("terser-webpack-plugin");
const Dotenv = require("dotenv-webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const isProductionMode = (mode) => mode === "production";
module.exports = () => {
const env = require("dotenv").config({ path: __dirname + "/.env" });
const nodeEnv = env.parsed.NODE_ENV;
return {
mode: "development",
entry: "./src/index.tsx",
output: {
path: path.join(__dirname, "./dist"),
filename: "[name].[contenthash].bundle.js",
publicPath: "/",
},
resolve: {
extensions: [".ts", ".tsx", ".js", "jsx", ".json"],
alias: {
"#api": path.resolve(__dirname, "src/api/"),
"#assets": path.resolve(__dirname, "src/assets/"),
"#components": path.resolve(__dirname, "src/components/"),
"#containers": path.resolve(__dirname, "src/containers/"),
"#data": path.resolve(__dirname, "src/data/"),
"#i18n": path.resolve(__dirname, "src/i18n/"),
"#models": path.resolve(__dirname, "src/models/"),
"#pages": path.resolve(__dirname, "src/pages/"),
"#src": path.resolve(__dirname, "src/"),
"#stores": path.resolve(__dirname, "src/stores/"),
"#utils": path.resolve(__dirname, "src/utils/"),
},
},
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: { loader: "babel-loader" },
},
{ test: /\.css$/, use: ["style-loader", "css-loader"] },
{ test: /\.(png|jpg|jpeg|gif)$/, use: ["file-loader"] },
{
test: /\.svg$/,
use: [
{
loader: "babel-loader",
},
{
loader: "react-svg-loader",
options: {
jsx: true,
},
},
],
},
],
},
devServer: {
historyApiFallback: true,
port: 3000,
inline: true,
hot: true,
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
}),
new Dotenv(),
],
optimization: {
minimize: isProductionMode(nodeEnv),
minimizer: isProductionMode(nodeEnv) ? [new TerserPlugin()] : [],
splitChunks: { chunks: "all" },
},
};
};
How to fix this? I am on webpack 5.24.2 and storybook 6.1.20, so these are the latest versions.

Just add this in your .storybook/main.js
const path = require('path');
module.exports = {
"stories": [
"../components/**/*.stories.mdx",
"../components/**/*.stories.#(js|jsx|ts|tsx)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials",
'#storybook/preset-scss',
],
webpackFinal: async (config, { configType }) => {
config.resolve.alias = {
...config.resolve.alias,
'#/interfaces': path.resolve(__dirname, "../interfaces"),
};
return config;
}
}
here interface is folder at my project root
It works For Me

This worked for me when I had the same problem:
Install a package in dev deps yarn add -D tsconfig-paths-webpack-plugin.
Then adjust your ./storybook/main.js config:
... // other imports
const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin");
...
webpackFinal: (config) => {
config.resolve.plugins = config.resolve.plugins || [];
config.resolve.plugins.push(
new TsconfigPathsPlugin({
configFile: path.resolve(__dirname, "../tsconfig.json"),
})
);
return { ... }
}
...

From the docs:
// .storybook/main.js
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
module.exports = {
webpackFinal: async (config) => {
config.resolve.plugins = [
...(config.resolve.plugins || []),
new TsconfigPathsPlugin({
extensions: config.resolve.extensions,
}),
];
return config;
},
};
Link

My React/TypeScript Storybook project uses Vite rather than Webpack.
The readme for storybook-builder-vite clarifies "The builder will not read your vite.config.js file by default," so anything that you specified in there may be having no influence whatsoever on the Storybook build; instead, you have to customise the Storybook-specific Vite config via the viteFinal option in .storybook/main.js.
Here's how I went about introducing vite-tsconfig-paths into the Storybook Vite config to resolve tsconfig path aliases:
// .storybook/main.js
const path = require("path");
const tsconfigPaths = require("vite-tsconfig-paths").default;
module.exports = {
"stories": [
"../frontend/**/*.stories.mdx",
"../frontend/**/*.stories.#(js|jsx|ts|tsx)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials",
"#storybook/addon-interactions"
],
"framework": "#storybook/react",
"core": {
"builder": "storybook-builder-vite"
},
/**
* A option exposed by storybook-builder-vite for customising the Vite config.
* #see https://github.com/eirslett/storybook-builder-vite#customize-vite-config
* #param {import("vite").UserConfig} config
* #see https://vitejs.dev/config/
*/
viteFinal: async (config) => {
config.plugins.push(
/** #see https://github.com/aleclarson/vite-tsconfig-paths */
tsconfigPaths({
// My tsconfig.json isn't simply in viteConfig.root,
// so I've passed an explicit path to it:
projects: [path.resolve(path.dirname(__dirname), "frontend", "tsconfig.json")],
})
);
return config;
},
}

In case you use #storybook/vite-builder. This neat config works for me
const tsconfigPaths = require("vite-tsconfig-paths");
...
module.exports = {
...
async viteFinal(config) {
return {
...config,
plugins: [...config.plugins, tsconfigPaths.default()],
};
},
};

If you're using webpack 5 you'll need to specify that webpack5 should be used by also adding the following in addition to the previous answers:
core: {
builder: "webpack5",
},
Final storybook/main.js would then resemble:
// .storybook/main.js
const path = require('path');
const appWebpack = require(path.join(process.cwd(), 'webpack.config.js'));
module.exports = {
stories: ['../src/**/*.stories.#(tsx|mdx)'],
addons: [
"#storybook/addon-links",
"#storybook/addon-essentials",
'#storybook/preset-scss'
],
core: {
builder: "webpack5",
},
webpackFinal: async (config) => {
config.resolve.modules = [
...(config.resolve.modules || []),
...[path.resolve(process.cwd(), "src")],
];
config.resolve.alias = {
...(config.resolve.alias || {}),
...appWebpack().resolve.alias,
};
return config;
},
};
This will allow both absolute paths as well as aliases (as long as those aliases are properly set up in your main webpack.config.js and jsconfig.json/tsconfig.json of course)
Edited
Having trouble after the fact specifically with aliases, I took another trip down the webpack rocky-road.
I've updated the original 'final' for the .storybook/main.js above, explicitly merging in the alias as well as the modules nodes.
Edit 2
Be aware, eslint is going to squawk over using an alias within global decorators you create (and add to .storybook/preview.js). You can safely ignore this - they still work. If/when I figure out how to correct this as well, I'll come back and add a 3rd edit.

We're using Vite and typescript project references, for us adding the following to the storybook main.cjs worked;
viteFinal: async (config) => {
config.resolve.alias = {
...config.resolve.alias,
'#some-alias': path.resolve(__dirname, '../../some/ts/project/reference'),
};
return config;
}

As an alternative to Jamie Birch's excellent answer, if you're using vite and don't want to install vite-tsconfig-paths, you can just edit .storybook/main.js and add viteFinal to the config, like this:
const path = require('path');
module.exports = {
// ... whatever you already have here
viteFinal: async (config) => {
if (config.resolve.alias) {
config.resolve.alias.push({ find: '#', replacement: path.resolve(__dirname, '../src') + '/' });
} else {
config.resolve.alias = [{ find: '#', replacement: path.resolve(__dirname, '../src') + '/' }];
}
return config;
}
}

Related

Webpack - TypeError: $ is not a function

i am new to webpack and i am creating a react application using webpack. I am getting this error while compiling TypeError: $ is not a function.
I am not using jquery but my node modules include some third party libraries.
I was only able to find one related article to this problem but it related to jquery.
Webpack - $ is not a function
Is there anything wrong with my webpack and babel config:
webpack.config.js
const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const FaviconsWebpackPlugin = require("favicons-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
module.exports = (env) => {
console.log("WEBPACK ENV: ", env);
const isDevMode = env !== "production";
let config = {
entry: ["./src/index.js"],
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].[contenthash].js"
},
resolve: {
extensions: [".js", ".jsx"]
},
plugins: [
new CleanWebpackPlugin(),
new FaviconsWebpackPlugin("./src/logo.png"),
new HtmlWebpackPlugin({
template: "./src/index.html",
minify: {
collapseInlineTagWhitespace: true,
collapseWhitespace: true,
removeComments: true,
removeRedundantAttributes: true
}
}),
new MiniCssExtractPlugin({
filename: "[name].[contenthash].css"
})
],
module: {
rules: [
{
test: /\.scss$/,
use: ["css-loader", "sass-loader"]
},
{
test: /\.jsx?$/,
exclude: /node_modules\/(?!(sdk1|sdk2)\/).*/,
use: ["babel-loader"]
},
{
test: /\.(ac3|gif|jpe?g|m4a|mp3|ogg|png|svg|otf)$/,
loader: "file-loader",
options: {
outputPath: "./assets"
}
}
]
},
optimization: {
minimize: true,
minimizer: [new OptimizeCssAssetsPlugin(), new TerserPlugin()],
splitChunks: {
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: "vendors",
chunks: "all"
}
}
}
}
};
// Mode
config.mode = isDevMode ? "development" : "production";
// Dev Tools
config.devtool = isDevMode ? "inline-source-map" : false;
// Plugins
if (!isDevMode) {
config.plugins.push(new BundleAnalyzerPlugin({ analyzerPort: 8181 }));
}
// Dev Server
if (isDevMode) {
config.devServer = {};
config.devServer.disableHostCheck = true;
}
return config;
};
babel.config.js
module.exports = {
plugins: [
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-transform-object-assign",
[
require.resolve("babel-plugin-module-resolver"),
{
root: ["./src/"],
alias: {
js: "./src/js",
scss: "./src/scss",
components: "./src/js/components",
containers: "./src/js/containers",
phaser_path: "./src/js/phaser",
services: "./src/js/services",
constants: "./src/js/constants"
}
}
]
],
presets: [
[
"#babel/preset-env",
{
useBuiltIns: "usage",
corejs: 3,
modules: false,
debug: true,
targets: {
browsers: [">0.25%", "ie >= 11"]
}
}
],
[
"#babel/preset-react",
{
development: true
}
]
]
};
I think it is related to the html-webpack-plugin but i don't know for sure. Any help is appreciated.
Thanks
I am currently using this as a workaround to polyfill for now as the useBuiltIns property is not working for me.
Installed the following packages: babel-polyfill, es6-promise, whatwg-fetch
npm i babel-polyfill
npm i --save-dev es6-promise whatwg-fetch
In webpack.config.js did these changes
Require es6-promise on top require("es6-promise").polyfill();
Add whatwg-fetch and babel-polyfill to the entry property in config like this
entry: ["whatwg-fetch", "babel-polyfill", "./src/index.js"]

On starting Styleguidedist server it fails with Module parse failed: Unexpected token

Im trying to start my style guide server but it keeps throwing following error:
I believe this occurs when the babel loaders are not configured for jsx files. But this isnt true as I am able to start my project without errors. But when I try to start the style guide I end up with this.
Here is my styleguide config file
module.exports = {
title: 'Component Library',
webpackConfig: Object.assign(
{},
require("./config/webpack/webpack.dev.config.js"),
{
/* Custom config options if required */
}
),
components: "source/components/**/*.jsx",
template: {
head: {
links: [
{
rel: "stylesheet",
href:
"https://fonts.googleapis.com/css?family=Poppins:400,400i,600,600i,700,700i&display=swap"
}
]
}
},
theme: {
fontFamily: {
base: '"Poppins", sans-serif'
}
},
styles: function styles(theme) {
return {
Playground: {
preview: {
backgroundColor: '#29292e'
},
},
Code: {
code: {
fontSize: 14,
},
},
};
},
};
Here is my webpack config
var webpack = require('webpack');
var path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
// const InterpolateHtmlPlugin = require('interpolate-html-plugin');
const WebpackAssetsManifest = require('webpack-manifest-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const reactLoadablePlugin = require('react-loadable/webpack')
.ReactLoadablePlugin;
const workboxPlugin = require('workbox-webpack-plugin');
module.exports = (env) => ({
mode: 'development',
entry: path.join(__dirname, '../../index.js'),
output: {
filename: '[name].bundle.[hash].js',
chunkFilename: '[name].bundle.[hash].js',
path: path.join(__dirname, '../../../build'),
publicPath: '/'
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
// cacheGroupKey here is `commons` as the key of the cacheGroup
name(module, chunks, cacheGroupKey) {
const moduleFileName = module
.identifier()
.split('/')
.reduceRight(item => item);
const allChunksNames = chunks.map(item => item.name).join('~');
return `${cacheGroupKey}-${allChunksNames}-${moduleFileName}`;
},
chunks: 'all'
}
}
}
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: path.resolve(__dirname, 'node_modules'),
loader: 'babel-loader'
},
{
test: /\.svg(\?.*)?$/, // match img.svg and img.svg?param=value
use: [
'url-loader', // or file-loader or svg-url-loader
'svg-transform-loader'
]
},
{
test: /\.png(\?.*)?$/, // match img.svg and img.svg?param=value
use: [
'url-loader', // or file-loader or svg-url-loader
]
},
{
test: /\.less$/,
use: [
'style-loader',
'css-loader',
{
loader: 'less-loader',
options: {
javascriptEnabled: true
}
}
]
},
{
test: /\.(sa|sc|c)ss$/,
exclude: path.resolve(__dirname, 'node_modules'),
use: [
'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
}
]
},
resolve: {
extensions: ['.js', '.jsx']
},
plugins: [
new webpack.EnvironmentPlugin({
APP_ENVIRONMENT: process.env.APP_ENVIRONMENT,
API_KEY: process.env.API_KEY,
AUTH_DOMAIN: process.AUTH_DOMAIN,
DB_URL: process.env.DB_URL,
PROJECT_ID: process.env.PROJECT_ID
}),
new CleanWebpackPlugin({
path: path.join(__dirname, '../../../build')
}),
new WebpackAssetsManifest({
fileName: 'asset-manifest.json'
}),
new HtmlWebpackPlugin({
title: '<<app>>',
template: 'main.html',
minify: {
collapseWhitespace: false,
removeComments: true,
useShortDoctype: false
}
}),
new MiniCssExtractPlugin({
filename: 'style.[contenthash].css'
}),
new CopyPlugin([
{
from: 'public',
to: 'public'
}
]),
new ProgressBarPlugin({
format: ' build [:bar] ' + ':percent' + ' (:elapsed seconds)' + ' :msg'
}),
new reactLoadablePlugin({
filename: './react-loadable.json'
}),
new workboxPlugin.InjectManifest({
swSrc: path.join(__dirname, '../../public/service-worker.js')
})
],
devServer: {
contentBase: path.join(__dirname, '/'),
filename: 'main.html',
compress: true,
port: 3000,
historyApiFallback: true,
disableHostCheck: true,
useLocalIp: true,
host: '0.0.0.0'
},
devtool: 'eval-source-map'
});
The problem was with the webpack file I was exporting the webpack configurations as a function.
Earlier:
module.exports = (env) => ({
....your webpack configurations
})
Instead of exporting everything as a function I exported it as
Now:
module.exports = {
....your webpack configurations
}
But can someone tell me why the earlier implementation didnt work?

Storybook UI with CSS modules and Less

Is it possible to use Storybook UI with React, CSS modules and Less? Have anyone managed to configure this kind of setup?
Adding .storybook/webpack.config.js helped me fix the issue, with
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader'],
}, {
test: /\.css$/,
use: {
loader: "css-loader",
options: {
modules: true,
}
}
}
],
},
}
I had same case. Resolved by adding webpackFinal to .storybook/main.js :
module.exports = {
stories: ['../src/**/*.stories.[tj]s'],
webpackFinal: async (config, { configType }) => {
config.module.rules.push(
{
test: /\.less$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
modules: true,
importLoaders: 1,
localIdentName: '[name]__[local]___[hash:base64:5]'
},
},
require.resolve('less-loader')
]
},
);
return config;
},
};
With sass as example:
Step 1: configure webpack in main.js. You can find documentation here: https://storybook.js.org/docs/configurations/custom-webpack-config/
const path = require('path');
module.exports = {
webpackFinal: async (config, { configType }) => {
// `configType` has a value of 'DEVELOPMENT' or 'PRODUCTION'
// You can change the configuration based on that.
// 'PRODUCTION' is used when building the static version of storybook.
// Make whatever fine-grained changes you need
config.module.rules.push({
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
include: path.resolve(__dirname, '../'),
});
// Return the altered config
return config;
},
stories: ['../stories/**/*.stories.js'],
};
Step 2: Install sass-loader
https://webpack.js.org/loaders/sass-loader/
Step 3: Create your scss files
#import "../stories/main.scss";
h1{color:$mediumBlue}
Modify your .storybook.main.js
module.exports = {
stories: ['../src/**/*.stories.js'],
addons: [
'#storybook/preset-create-react-app',
'#storybook/addon-actions',
'#storybook/addon-links',
],
webpackFinal: async (webpackConfig, { configType }) => {
// `configType` has a value of 'DEVELOPMENT' or 'PRODUCTION'
// You can change the configuration based on that.
// 'PRODUCTION' is used when building the static version of storybook.
const { loadCracoConfig } = require('#craco/craco/lib/config');
const { getCraPaths } = require('#craco/craco/lib/cra');
const context = {env: process.env.NODE_ENV};
const cracoConfig = loadCracoConfig(context);
context.paths = getCraPaths(cracoConfig);
const {overrideWebpackConfig} = require('#semantic-ui-react/craco-less');
overrideWebpackConfig({
context,
webpackConfig
});
// Return the altered config
return webpackConfig;
},
};
This is taken from node_modules/#craco/craco/scripts/start.js
localIdentName option moved in css-loader configuration so this is the new configuration.
source: https://github.com/rails/webpacker/issues/2197#issuecomment-517234086
module.exports = {
stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.#(js|jsx|ts|tsx)'],
webpackFinal: async (config) => {
config.module.rules.push({
test: /\.less$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
modules: {
localIdentName: '[name]__[local]___[hash:base64:5]',
},
},
},
require.resolve('less-loader'),
],
});
return config;
},
};

What's best way to config React components library with Webpack, typescript, css modules and SASS

I'm config a React components library for reuses in other our projects. I want to use these:
Typescript for components
Css modules
Sass
Webpack for bundle
So this is my webpack config:
const childProcess = require('child_process');
const path = require('path');
const url = require('url');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const loadersConf = require('./webpack.loaders');
const NPM_TARGET = process.env.npm_lifecycle_event; //eslint-disable-line no-process-env
const targetIsRun = NPM_TARGET === 'run';
const targetIsTest = NPM_TARGET === 'test';
const targetIsStats = NPM_TARGET === 'stats';
const targetIsDevServer = NPM_TARGET === 'dev-server';
const DEV = targetIsRun || targetIsStats || targetIsDevServer;
const STANDARD_EXCLUDE = [
path.join(__dirname, 'node_modules'),
];
// These files will be imported in every sass file
const sassResourcesPaths = [
path.resolve(__dirname, 'src/styles/abstracts/_variables.sass'),
path.resolve(__dirname, 'src/styles/abstracts/_mixins.sass'),
];
const config = {
module: {
rules: loadersConf,
},
resolve: {
modules: [
'node_modules',
path.resolve(__dirname),
],
extensions: ['.js', '.jsx', '.ts', '.tsx', '.css', '.scss'],
},
performance: {
hints: 'warning',
},
target: 'web',
plugins: [
new webpack.DefinePlugin({
COMMIT_HASH: JSON.stringify(childProcess.execSync('git rev-parse HEAD || echo dev').toString()),
}),
new MiniCssExtractPlugin({
filename: '[name].[contentHash].css',
chunkFilename: '[name].[contentHash].css',
}),
],
};
if (DEV) {
config.mode = 'development';
config.devtool = 'source-map';
}
const env = {};
if (DEV) {
} else {
env.NODE_ENV = JSON.stringify('production');
}
config.plugins.push(new webpack.DefinePlugin({
'process.env': env,
}));
module.exports = config;
And this is loaders for webpack:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const STANDARD_EXCLUDE = [
path.join(__dirname, 'node_modules'),
];
const NPM_TARGET = process.env.npm_lifecycle_event; //eslint-disable-line no-process-env
const targetIsRun = NPM_TARGET === 'run';
const targetIsTest = NPM_TARGET === 'test';
const targetIsStats = NPM_TARGET === 'stats';
const targetIsDevServer = NPM_TARGET === 'dev-server';
const DEV = targetIsRun || targetIsStats || targetIsDevServer;
// noinspection WebpackConfigHighlighting
module.exports = [
{
test: /\.(js|jsx|ts|tsx)?$/,
exclude: STANDARD_EXCLUDE,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
// Babel configuration is in .babelrc because jest requires it to be there.
},
},
},
{
type: 'javascript/auto',
test: /\.json$/,
include: [
path.resolve(__dirname, 'i18n'),
],
exclude: [/en\.json$/],
use: [
{
loader: 'file-loader?name=i18n/[name].[hash].[ext]',
},
],
},
// ==========
// = Styles =
// ==========
// Global CSS (from node_modules)
// ==============================
{
test: /\.css/,
include: path.resolve(__dirname, "node_modules"),
use: [
MiniCssExtractPlugin.loader,
{
loader: "style-loader"
},
{
loader: 'css-loader'
}
]
},
{
test: /\.(sc|sa|c)ss$/,
exclude: /\.st.css$/, //This must appear before the "oneOf" property
use: [
MiniCssExtractPlugin.loader,
'style-loader',
'css-modules-typescript-loader',
{
loader: 'css-loader',
options: {
importLoaders: 2,
modules: true,
camelCase: "dashes",
localIdentName: DEV
? '[name]__[local]___[hash:base64:5]'
: '_[hash:base64:5]',
},
},
{
loader: "postcss-loader",
options: {
sourceMap: "inline",
extract: true,
}
},
"sass-loader",
],
},
{
test: /\.(png|eot|tiff|svg|woff2|woff|ttf|gif|mp3|jpg)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'files/[hash].[ext]',
},
},
{
loader: 'image-webpack-loader',
options: {},
},
],
},
];
Babel config:
const config = {
presets: [
['#babel/preset-env', {
targets: {
chrome: 66,
firefox: 60,
edge: 42,
safari: 12,
},
modules: false,
corejs: 3,
useBuiltIns: 'usage',
shippedProposals: true,
}],
['#babel/preset-react', {
useBuiltIns: true,
}],
['#babel/typescript', {
allExtensions: true,
isTSX: true,
}],
],
plugins: [
'#babel/plugin-transform-runtime',
'#babel/plugin-syntax-dynamic-import',
'#babel/proposal-class-properties',
'#babel/proposal-object-rest-spread',
'#babel/plugin-proposal-optional-chaining',
['module-resolver', {
root: ['./src', './test'],
}],
],
};
// Jest needs module transformation
config.env = {
test: {
presets: config.presets,
plugins: config.plugins,
},
};
config.env.test.presets[0][1].modules = 'auto';
module.exports = config;
This is a demo component of this library:
import React from 'react';
const styles = require('./style.scss');
type Props = {
children?: React.ReactNode;
openLeft?: boolean;
openUp?: boolean;
id?: string;
ariaLabel: string;
customStyles?: object;
}
export default class Button extends React.PureComponent<Props> {
public render() {
return (
<button className={styles.test}>
{this.props.children}
</button>
);
}
}
So, this is develop build command:
"build": "cross-env NODE_ENV=production webpack --display-error-details --verbose",
"run": "webpack --progress --watch",
when I using this library:
import ExampleComponent from 'mylibrary';
When I run BUILD or RUN command, the javascript is built, but not SCSS. So in my other project, the build throw an error:
can not find module './style.scss'
This error occur in ExampleComponent
Please tell me how to resolve it. Thanks you very much!
This is my webpack config for the styles part:
{
test: /\.s?css$/,
use: [
{
loader: MiniCssExtractPlugin.loader
},
{
loader: 'css-loader'
},
{
loader: 'postcss-loader',
options: {
config: {
path: 'postcss.config.js'
}
}
},
{
loader: 'sass-loader'
},
]
}
and in my postcss.config.js:
module.exports = {
plugins: [
require('autoprefixer')
]
}

how to solve this error You may need an appropriate loader to handle this file type

I got this error with this library https://github.com/react-native-web-community/react-native-web-linear-gradient/
the error link
https://github.com/react-native-web-community/react-native-web-linear-gradient/issues/1
details of error:
Module parse failed: Unexpected token (5:22)
You may need an appropriate loader to handle this file type.
my webpack:
'use strict';
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getClientEnvironment = require('./env');
const paths = require('./paths');
const publicPath = '/';
const publicUrl = '';
const env = getClientEnvironment(publicUrl);
module.exports = {
devtool: 'cheap-module-source-map',
entry: [
require.resolve('./polyfills'),
require.resolve('react-dev-utils/webpackHotDevClient'),
paths.appIndexJs,
],
output: {
pathinfo: true,
filename: 'static/js/bundle.js',
chunkFilename: 'static/js/[name].chunk.js',
publicPath: publicPath,
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
},
resolve: {
modules: ['node_modules', paths.appNodeModules].concat(
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
alias: {
'babel-runtime': path.dirname(
require.resolve('babel-runtime/package.json')
),
'react-native': 'react-native-web',
'react-native-linear-gradient': 'react-native-web-linear-gradient'
},
plugins: [
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
module: {
strictExportPresence: true,
rules: [
{
test: /\.(js|jsx|mjs)$/,
enforce: 'pre',
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve('eslint'),
baseConfig: {
extends: [require.resolve('eslint-config-react-app')],
},
ignore: false,
useEslintrc: false,
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
{
oneOf: [
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
{
test: /\.(js|jsx|mjs)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
babelrc: false,
presets: [require.resolve('babel-preset-react-app')],
cacheDirectory: true,
},
},
{
test: /\.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
],
},
{
exclude: [/\.js$/, /\.html$/, /\.json$/],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
],
},
],
},
plugins: [
new InterpolateHtmlPlugin(env.raw),
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),
new webpack.NamedModulesPlugin(),
new webpack.DefinePlugin(env.stringified),
new webpack.HotModuleReplacementPlugin(),
new CaseSensitivePathsPlugin(),
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
},
performance: {
hints: false,
},
};
the class who make the problem:
import React, { PureComponent } from 'react';
import { View } from 'react-native';
export default class LinearGradient extends PureComponent {
static defaultProps = {
start: {
x: 0.5,
y: 0,
},
end: {
x: 0.5,
y: 1,
},
locations: [],
colors: [],
};
state = {
width: 1,
height: 1,
};
measure = ({ nativeEvent }) =>
this.setState({
width: nativeEvent.layout.width,
height: nativeEvent.layout.height,
});
getAngle = () => {
// Math.atan2 handles Infinity
const angle =
Math.atan2(
this.state.width * (this.props.end.y - this.props.start.y),
this.state.height * (this.props.end.x - this.props.start.x)
) +
Math.PI / 2;
return angle + 'rad';
};
getColors = () =>
this.props.colors
.map((color, index) => {
const location = this.props.locations[index];
let locationStyle = '';
if (location) {
locationStyle = ' ' + location * 100 + '%';
}
return color + locationStyle;
})
.join(',');
render() {
return (
<View
style={[
this.props.style,
{ backgroundImage: `linear-gradient(${this.getAngle()},${this.getColors()})` },
]}
onLayout={this.measure}
>
{this.props.children}
</View>
);
}
}
static defaultProps and ()=> make the bug so what could be wrong?
Partial fix >>
Steps:
1-npm install babel babel-cli --save-dev on the library
2-I add "transpile": "babel src/index.js --out-file src/index-transpiled.js"
in package.json scripts
3-yarn transpile
4-I moved the ES5 file to my code and it worked
Update - Full Fix
I included my src folder and the libraries to babel too
// Process JS with Babel.
{
test: /\.(js|jsx|mjs)$/,
include: [
/src\/*/,
/node_modules\/react-native-/,
],
loader: require.resolve('babel-loader'),
options: {
babelrc: false,
presets: [require.resolve('babel-preset-react-native')],
cacheDirectory: true
}
},
I think this is because of ES7 feature. Do you have stage-0 installed & added to your .babelrc or webpack.config.js file?
Here how you can do it:
npm i --save-dev babel-preset-stage-0
And then you should include it into webpack.config.js file like below:
loader: "babel-loader", // or just "babel"
query: {
presets: [ <other presets>, 'stage-0']
}
Or add it to .babelrc file:
{
"presets": ["stage-0"]
}
UPDATE
As I said earlier the issue belongs to ES7 feature. Seems like webpack can not resolve static keyword within react-native-web-linear-gradient module. So what I did to fix this issue:
I copied the source code from react-native-web-linear-gradient into my own component called LinearGradient. I didn't change anything within it.
I installed stage-0 and added it to .babelrc as i described above.
Later instead of using react-native-web-linear-gradient i use my LinearGradient component.
As a result i got gradient on my page. git project link.
Hope it will help!
This is how webpack can be configured to load assets, such as images (pngs, svgs, jpgs and so on):
npm install --save-dev file-loader
Add this in the webpack.config.js, under the module.exports.rules:
{
test: /\.(png|svg|jpg|gif)$/,
use: ["file-loader"]
}
Now, when you import MyImage from './my-image.png', that image will be processed and added to your output directory and the MyImage variable will contain the final url of that image after processing.

Resources