How to integrate Material UI into Svelte project - material-ui

I want to integrate Material UI into my Svelte project.
I tried to follow the official documentation from here, but I don't know why I'm getting a strange error while trying to run my project:
loaded rollup.config.js with warnings
(!) Unused external imports
default imported from external module 'rollup-plugin-postcss' but never used
rollup v1.27.13
bundles src/main.js → public/build/bundle.js...
[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
src/views/App.css (1:0)
1: .footer.svelte-1xl6ht0{position:fixed;left:0;bottom:0;width:100%;background-color:#569e3e;color:white;text-align:center;height:15px}.footer.us.svelte-1xl6ht0,.footer.europe.svelte-1xl6ht0,.footer.central.svelte-1xl6ht0,.footer.south.svelte-1xl6ht0,.footer.apac.svelte-1xl6ht0,.footer.baldr.svelte-1xl6ht0{background-color:#ca4a4a}.footer
....
The problem seems to be related to CSS.
In my src directory I have a directory called theme which contains a file called _smui-theme.scss and this is the content of the file:
#import "#material/theme/color-palette";
// Svelte Colors!
$mdc-theme-primary: #ff3e00;
$mdc-theme-secondary: #676778;
// Other Svelte color: #40b3ff
$mdc-theme-background: #fff;
$mdc-theme-surface: #fff;
$mdc-theme-error: $material-color-red-900;
And here is my rollup.config.json file:
import svelte from 'rollup-plugin-svelte';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import json from '#rollup/plugin-json';
const production = !process.env.ROLLUP_WATCH;
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js',
},
plugins: [
json(),
svelte({
// Enables run-time checks when not in production.
dev: !production,
// Extracts any component CSS out into a separate file — better for performance.
css: css => css.write('public/build/bundle.css'),
// Emit CSS as "files" for other plugins to process
emitCss: true,
}),
resolve({
browser: true,
dedupe: importee => importee === 'svelte' || importee.startsWith('svelte/')
}),
commonjs(),
// In dev mode, call `npm run start` once the bundle has been generated
!production && serve(),
// Watches the `public` directory and refresh the browser on changes when not in production.
!production && livereload('public'),
// Minify for production.
production && terser()
],
watch: {
clearScreen: false
}
};
function serve() {
let started = false;
return {
writeBundle() {
if (!started) {
started = true;
require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
}
}
};
}

In order to solve this issue a postcss plugin is needed for rollup.
I have also added a svelte preprocessor (I think this is optional, but I wanted to be sure).
Make sure you install this packages with npm or yarn:
rollup-plugin-postcss and svelte-preprocess
Then the plugins should be added in rollup.config.js like this:
import svelte from 'rollup-plugin-svelte';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import postcss from 'rollup-plugin-postcss'; <<<------------- Add this
import autoPreprocess from 'svelte-preprocess'; <<<------------- Add this
import json from '#rollup/plugin-json';
const production = !process.env.ROLLUP_WATCH;
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js',
},
plugins: [
json(),
svelte({
// Enables run-time checks when not in production.
dev: !production,
// Extracts any component CSS out into a separate file — better for performance.
css: css => css.write('public/build/bundle.css'),
// Emit CSS as "files" for other plugins to process
emitCss: true,
preprocess: autoPreprocess() <<<------------- Add this
}),
resolve({
browser: true,
dedupe: importee => importee === 'svelte' || importee.startsWith('svelte/')
}),
commonjs(),
postcss({ <<<------------- Add this
extract: true,
minimize: true,
use: [
['sass', {
includePaths: [
'./src/theme',
'./node_modules'
]
}]
]
}),
// In dev mode, call `npm run start` once the bundle has been generated
!production && serve(),
// Watches the `public` directory and refresh the browser on changes when not in production.
!production && livereload('public'),
// Minify for production.
production && terser()
],
watch: {
clearScreen: false
}
};
function serve() {
let started = false;
return {
writeBundle() {
if (!started) {
started = true;
require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
}
}
};
}
Now everything should be working right with the css and Material UI can be used.

Related

Unable to resolve module when using babel module resolver + eslint + index files in react application

I am trying to use babel module resolver plugin with eslint + create react app but I am unable to start the application, getting the error
internal/modules/cjs/loader.js:1237
throw err;
^
SyntaxError: C:\Users\enisr\Desktop\projects\pcPartPicker\jsconfig.json:
Unexpected token } in JSON at position 166
at parse (<anonymous>)
I have set up a git repo showcasing the problem https://github.com/sgoulas/pcPartPicker
I have read the instructions in the docs and in the original repository and I am unable to configure it correctly.
My configuration files are the following:
.babelrc
{
"plugins": [
["module-resolver", {
"extensions": [
".js",
".jsx",
".es",
".es6",
".mjs"
],
"root": ["./src"],
"alias": {
"#components": "./src/components"
}
}
]
]
}
jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": ["src/*"],
"#components/*": ["./src/components/*"],
}
}
}
webpack.config.dev.js
var path = require("path");
module.exports = {
include: path.appSrc,
loader: require.resolve("babel-loader"),
options: {
plugins: [
[
"module-resolver",
{
root: ["./src/App"],
alias: {
"#components": "./src/components",
},
},
],
],
cacheDirectory: true,
},
};
My component:
import { GPUtable, CPUtable } from "#components/Tables";
const App = () => {
return (
<>
<GPUtable />
<CPUtable />
</>
);
};
export default App;
There are some minor fixes you need to make (below), but the main issue is that Create React App does not expose the webpack config, you'll need to eject to edit that.
npm run eject
Merge the babel configs: delete the babel key + value at the bottom of the package.json, and paste the value into your bablrc ("presets": ["react-app"],).
Add import React from 'react'; to the top of App.js
Confirmed locally that the app will run.
Other suggested fixes
Your jsconfig has a trailing comma after the array value in #components/*. You need to remove it because JSON doesn’t support them.
You need to fix the include path in weback.config.dev.js. appSrc isn't something defined on the node path module. Try using path.resolve(__dirname, 'src') - the example in their docs is creating/importing a paths object with appSrc pointing to this value.
You're missing test: /\.(js|jsx|mjs)$/, in webpack.config.dev.js.

Troubles combining bundling Svelte Material UI with custom SCSS using Rollup

I have Svelte 3.x (with TS enabled) and a pretty standard Rollup config for bundling my SCSS files with this file structure:
| src
| styles.scss
| etc.
rollup.config.js:
export default {
input: 'src/main.ts',
output: {
sourcemap: true,
format: 'iife',
name: 'myapp',
file: 'public/build/bundle.js'
},
plugins: [
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file - better for performance
css: css => {
css.write('bundle.css');
},
preprocess: autoPreprocess(),
}),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
typescript({ sourceMap: !production }),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser()
],
watch: {
clearScreen: false
}
};
This works fine. Now I'm struggling getting Svelte Material UI running.
After installing postcss, rollup-plugin-postcss, rollup-plugin-sass, svelte-material-uiand svelte-preprocess-sass and reading through here and there and there I added this to the plugins array in rollup.config.js:
postcss({
extract: true,
minimize: true,
use: [
['sass', {
includePaths: [
'./src/theme',
'./node_modules'
]
}]
]
})
When I test it in my app using a #smui/button the button (with a default styling and the default ripple effect) works, but none of my SCSS gets compiled (or get overwritten during bundling).
I'm searching the needle in the haystack and appreciate any hint.
Got it, I just missed adding emitCss: true in the Svelte plugin config. So my working rollup.config.js is this:
export default {
input: 'src/main.ts',
output: {
sourcemap: true,
format: 'iife',
name: 'myapp',
file: 'public/build/bundle.js'
},
plugins: [
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file - better for performance
css: css => {
css.write('bundle.css');
},
emitCss: true,
preprocess: autoPreprocess()
}),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
typescript({ sourceMap: !production }),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser()
],
watch: {
clearScreen: false
}
};
This also has been answered here.

Jest Test Support for the experimental syntax 'jsx' isn't currently enabled

I am writing first tests for my app and just install Jest.
My test is pretty simple, so I don't think the error I am getting is coming from there.
import React from 'react';
import renderer from 'react-test-renderer';
import FancyInput from './FancyInput';
describe('FancyInput', () => {
it('should render correctly', () => {
expect(
renderer.create(
<FancyInput />
)
).toMatchSnapshot();
});
});
Error when run the test is Support for the experimental syntax 'jsx' isn't currently enabled
also
`Add #babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add #babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.`
My webpack file has the following thing:
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-react',
],
plugins: [
["#babel/plugin-proposal-decorators", { "legacy": true }],
["#babel/plugin-proposal-optional-chaining"],
["#babel/plugin-syntax-jsx"],
]
}
}
},
also my package.json has all the plugins I believe are necessary
"#babel/plugin-proposal-class-properties": "^7.10.4",
"#babel/plugin-proposal-decorators": "^7.4.4",
"#babel/plugin-proposal-optional-chaining": "^7.11.0",
"#babel/plugin-syntax-jsx": "^7.10.4",
"#babel/preset-react": "^7.0.0",
what am I missing here ?

Using a Svelte build with a Sails node server

I am trying to set up a website with Svelte for the frontEnd and Sails for the backend.
My problem is that I can't display my Svelte public build as my Sails default web page.
I want to keep the organization below (or maybe something similar) and have my Svelte public build page when I go on 'http://myserver:1337' instead of having the default Sails page : file organization
PS: I am using Node: v14.4.0, Sails: v1.2.4 and Svelte: v6.14.5.
Thank you all :)
You could try something like:
Compile Svelt to build into the /public directory on Sails.js.
Open your rollup.config.js and change the path of your public/build/bundle.js and public/build.bundle.css to the public sails path, i.e. "../server/public...".
Configure /task/pipeline.js to include the compiled js and css files:
// tasks/pipeline.js
var cssFilesToInject = [
'css/**/global.css',
'css/**/bundle.css',
'css/**/*.css',
];
var jsFilesToInject = [
'js/**/bundle.js',
'js/**/*.js'
];
Create a controller to load the index file:
// router.js
'/*': { action: 'index', skipAssets: true, skipRegex: /^\/api\/.*$/ },
The excluded "/api" routes is to allow you to configure the CRUD routes.
The index controller:
module.exports = {
friendlyName: 'View homepage',
description: 'Display a compiled index page',
exits: {
success: {
statusCode: 200,
viewTemplatePath: 'pages/index'
},
},
fn: async function () {
return {};
}
};
And the index page you could include the template index.html or create your own index.ejs to load the static content, the same you configured before:
// views/templates/template.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width,initial-scale=1'>
<title>Svelte app</title>
<link rel='icon' type='image/png' href='/favicon.png'>
<!--STYLES-->
<!--STYLES END-->
</head>
<body>
<!--TEMPLATES-->
<!--TEMPLATES END-->
<%- body %>
<!-- exposeLocalsToBrowser ( ) %>
<!--SCRIPTS-->
<!--SCRIPTS END-->
</body>
</html>
And the index.ejs:
// views/pages/index.ejs
<!-- Nothing here I mean -->
Thank you for your answer it helps me to understand how does it works.
I am sorry but I did not follow your tutorial exactly (because I was not able to understand what I was supposed to do ;) ).
I edit the rollup.config.js as :
import svelte from 'rollup-plugin-svelte';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
const production = !process.env.ROLLUP_WATCH;
const BUILD_PATH = '../server/assets';
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: `${BUILD_PATH}/build/bundle.js`
},
plugins: [
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file - better for performance
css: css => {
css.write(`${BUILD_PATH}/build/bundle.css`);
}
}),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload(BUILD_PATH),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser()
],
watch: {
clearScreen: false
}
};
function serve() {
let started = false;
return {
writeBundle() {
if (!started) {
started = true;
require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
}
}
};
}
And I move my files is the assets as :
file organization
Then I deleted the homepage.ejs in server/views/pages/
And it works :) !
Thank you again for your quick answer

How to set up rollup with karma and babel?

I try to set up rollup with karma and babel for test.
I face two problems.
First, it cause error Uncaught TypeError about default.
Uncaught TypeError: Cannot use 'in' operator to search for 'default' in undefined
Second, it doesn't find external dependency.
Treating 'chai' as external dependency
What's wrong in my settings?
rollup conf
import babel from "rollup-plugin-babel";
import babelrc from "babelrc-rollup";
import istanbul from "rollup-plugin-istanbul";
import nodeResolve from "rollup-plugin-node-resolve";
import commonjs from "rollup-plugin-commonjs";
import builtins from "rollup-plugin-node-builtins";
import globals from "rollup-plugin-node-globals";
// import uglify from 'rollup-plugin-uglify'
let pkg = require('./package.json');
let external = Object.keys(pkg.dependencies);
export default {
entry: 'src/index.js',
plugins: [
babel(babelrc()),
istanbul({
exclude: ['test/**/*', 'node_modules/**/*']
}),
globals(),
builtins(),
nodeResolve({
module: true,
jsnext: true,
main: true,
browser: true,
extensions: ['.js']
}),
commonjs({
include: 'node_modules/**'
}),
//uglify(),
],
external: external,
targets: [
{
dest: pkg.main,
format: 'umd',
moduleName: 'sketchbook',
sourceMap: true
},
{
dest: pkg.module,
format: 'es',
sourceMap: true
}
]
};
karma conf
module.exports = function (config) {
config.set({
files: [
// Watch src files for changes but
// don't load them into the browser.
{pattern: 'src/**/*.js', included: false},
'test/**/*.spec.js',
],
browsers: ['Chrome'],
preprocessors: {
'src/**/*.js': ['rollup'],
'test/**/*.spec.js': ['rollup'],
},
rollupPreprocessor: {
plugins: [
require('rollup-plugin-buble')(),
],
format: 'umd', // Helps prevent naming collisions.
moduleName: 'sketchbook', // Required for 'iife' format.
sourceMap: 'inline', // Sensible for testing.
},
customPreprocessors: {
// Clones the base preprocessor, but overwrites
// its options with those defined below.
rollupBabel: {
base: 'rollup',
options: {
// In this case, to use
// a different transpiler:
plugins: [
require('rollup-plugin-babel')(),
],
}
}
}
// frameworks: ['mocha'],
// client: {
// mocha: {
// opts: 'test/mocha.opts'
//
// // // change Karma's debug.html to the mocha web reporter
// // reporter: 'html',
// //
// // // require specific files after Mocha is initialized
// // require: [require.resolve('bdd-lazy-var/bdd_lazy_var_global')],
// //
// // // custom ui, defined in required file above
// // ui: 'bdd-lazy-var/global',
// }
// }
});
};
source