How to transpile node_modules with Turborepo and SWC - next.js

next-transpile-modules works great for Next projects, but how do I transpile modules for a raw SWC build??? I stumped 😭
Repo: https://github.com/deltaepsilon/script-kitty
I started from a Turborepo base and exported two packages, ui and command-k into a Turborepo Next app named web. Everything worked great once I added ui and command-k to the next.config.js file like so:
const withTM = require('next-transpile-modules')(['command-k', 'ui']);
module.exports = withTM({
reactStrictMode: true,
});
Now I've got a new app named external that's going to be a standalone build of the command-k package. This will get published to npm.
I'm using swc-loader to transpile it with the following config:
const path = require('path');
// See https://github.com/iykekings/react-swc-loader-template
const config = {
mode: 'development',
entry: './index.tsx',
module: {
rules: [
{
test: /\.(ts|tsx)$/,
loader: 'swc-loader',
include: [
path.resolve(__dirname),
path.resolve(__dirname, '../../packages/command-k'),
path.resolve(__dirname, '../../packages/ui'),
],
exclude: /node_modules/,
},
],
},
};
module.exports = config;
I keep getting the following error when building with yarn dev:
ERROR in ../../packages/command-k/index.tsx 2:0-50
Module not found: Error: Can't resolve './command-k' in '/kitty/packages/command-k'
resolve './command-k' in '/kitty/packages/command-k'
using description file: /kitty/packages/command-k/package.json (relative path: .)
// /packages/command-k/index.tsx
import * as React from 'react';
export { default as CommandK } from './command-k';
It looks like swc-loader is somehow unable to import from inside of a Turborepo package. It works fine if I inline the contents of ./command-k into /packages/command-k/index.tsx, but swc-loader refuses to follow the import.

Related

NextJs 'npm build' and 'npm start' messes up styles

I'm using NextJs for a project (Unfortunately I'm not allowed to share screenshots). When I run 'npm run dev' for development, the website works as expected. But when I run 'npm run build' and 'npm start', I see overlapping components as if something is wrong with the CSS. What could be the issue? Thanks in advance!
Update
There is conflicting ordering in my CSS imports, says the mini-css-extract-plugin. I think that's what messes the website up. But still not sure how to fix it
I faced few css issues last week and i came across mini-css-extract-plugin, and read in article that css loaders has to be used. Here is my next.config.js check whether this would help. If you see here i have added that mini-css-extract-plugin but then i commented it out. Adding these loaders: ['style-loader', 'css-loader', 'less-loader'] and having all css in _app.js and proper SSR based materialUI styling in _document.js
const withImages = require('next-images')
module.exports = withImages()
// const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const withCSS = require('#zeit/next-css')
const withLess = require('#zeit/next-less')
const withSass = require("#zeit/next-sass");
module.exports = withImages({
target: 'serverless',
webpack: function (config, { webpack }) {
config.module.rules.push({
test: /\.(eot|svg|gif|md)$/,
// use: 'raw-loader',
// test: /\.(sass|less|css)$/,
loaders: ['style-loader', 'css-loader', 'less-loader']
})
config.plugins.push(new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
ENV: JSON.stringify(process.env.ENV),
}
}))
return config
},
})

Unable to load CSS correctly for external library in Storybook Angular

I am using Angular with Projects style setup (with --create-application=false) and I just cannot get Storybook to load any CSS from external libraries like Angular Material. The project component scss compiles and works fine but none of the external libraries can load any css.
Here is my storybook/main.js -
const path = require('path');
module.exports = {
"stories": [
"../stories/**/*.stories.mdx",
"../stories/**/*.stories.#(js|jsx|ts|tsx)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials"
],
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;
}
}
Here is my project structure -
Can someone please point out what the problem is?

Firebase hosting showing generic message

I was building a WhatsApp clone app (https://github.com/adrielwerlich/curso-hcode-whatsapp-clone)
running the build command
run the firebase deploy --only hosting command
But this screen is what I´m getting
And the Firebase dashboard is displaying
Update
I was able to make some advances.
I added to
webpack.config.js
new HtmlWebpackPlugin({
template: './index.html',
})
and now there is proper html content...
but the app.bundle.js is giving a error message when I try to use firebase serve
After discovering that the bundle was only creating the js files, and was necessary to also configure the HtmlWebpackPlugin to create the HTML file the problem was to make the js files visible to the html files.
So the final solution to make the bundle run inside local firebase serve command and remote firebase hosting service...
The whole issue was about the webpack bundle config
webpack.config.js
const path = require('path')
var HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry:{
app:'./src/app.js',
'pdf.worker':'pdfjs-dist/build/pdf.worker.entry.js'
},
output:{
filename:'[name].bundle.js',
path: path.join(__dirname, '/dist'),
publicPath:'/' // the issue was here. Instead of /dist only / makes the js bundle files visible inside the html index file
},
module: {
loaders: [
{
test: /\.css/,
loaders: ['style-loader', 'css-loader']
// include: __dirname + '/'
},
{
test: /.(gif|png|jpe?g|webp|svg)$/i,
use: [
'file-loader',
{
loader: 'image-webpack-loader',
options: {
webp: {
quality: 80
}
}
}
]
}
],
},
plugins: [
new HtmlWebpackPlugin({
template: './index.html',
})
]
}
and also had to configure de css-style loader and the image webpack loader in order to run properly inside firebase localhost server and firebase remote hosting service
Suffering with the small details of bundle builder configuration... many hours of anxiety...

How to integrate WordPress into Webpack?

I developed a website front-end using HTML/CSS, JavaScript and Sass or Scss. I used NPM.
I need to put that website into WordPress. I already installed WordPress and put that folder with all my assets(HTML/CSS, JS, Sass etc..) into theme folder.
Now, what do I do now? How do I connect all of this?
I know it's possible because I have worked on a site like this before at work, but not sure how to do it from the ground up.
Webpack -> WordPress. I will watch the files with NPM or webpack, but the hosting will be doing with MAMP - that's how I did it at work anyways.
What should I do?
This is the website code if anything: https://github.com/AurelianSpodarec/lovetocodefinal
PS, no WordPress API or any stuff like that, but just as I wrote above.
I found a solution to this.
It's simple. You need to compile everything and put it in the folders that will be used by WordPress and do WordPress magic to get the styles with functions.
I have made this here: https://github.com/AurelianSpodarec/Webpack-to-WordPress-Starting-Template
It's not perfect, but a good starting point for those who are looking on using Webpack with WordPress.
Old Question, but just had the same one myself. I just built a light Wordpress-Webpack starter. You can use it to build Wordpress-Themes and it will build Scss and copy PHP etc. into the destination of your Themes. It uses Browsersync for easier development. You have complete separation of dev and build :) Maybe this can still help in future. Regards, Fabian
Link: https://github.com/fabiankuhn/webpack-wordpress
Extract from Main Build config (Paths):
const themeName = 'test-theme'
const themePath = '/Users/<Username>/<repos>/Test/webpack/wordpress/wp-content/themes'
/*
* Main Config
*/
module.exports = {
entry: './webpack-entry.js', // Main Entry: Is included in functions.php
output: {
filename: 'main.js', // Is included in functions.php
// Set Path of Wordpress Themes ('.../wp-content/themes') as absolute Path
path: themePath + '/' + themeName + '/assets',
},
Extract from Wordpress webpack config:
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin')
// This Config Exports the FIles with Source Maps for Wordpress Development
module.exports = merge(common, {
mode: 'development',
devtool: 'inline-source-map', // Use Source-Maps for Debug
plugins: [
// Plugin to Reload Browser According to Proxy 127.0.0.1:8080 (Wordpress PHP)
new BrowserSyncPlugin({
host: 'localhost',
port: 3000,
proxy: '127.0.0.1:8080',
files: [
{
match: [
'**/*.php',
'**/*.js',
'**/*.css',
],
},
],
notify: false,
},
{
reload: true,
}),
// Extract CSS
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css',
}),
// Copy all Files to Entry Output Path except Github, Webpack and
// Original Sources (Before Webpack Processing)
new CopyPlugin([
{
from: '../',
to: '../',
ignore: [
'_webpack/**',
'assets/**',
'.git/**',
],
},
]),
],
module: {
rules: [
{
// Listen for Sass and CSS
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
},
},
// Source Map shows Path in Chrome for Testing
{ loader: 'css-loader', options: { sourceMap: true, importLoaders: 1 } },
{ loader: 'sass-loader', options: { sourceMap: true } },
],
},
],
},
});

.Net Core 2 Spa Template with Angular Material

Struggling trying to get Angular Material , or any 3rd party control set really, to work with this new template. In this new template, the webpack is broken into TreeShakable and NonTreeShakable. In addition the app.module is now app.module.shared, app.module.browser, app.module.server.
As I have attempted to get this to work, the app will only run with modules configured in app.module.browser, but the material tags are not getting processed. Trying something simple and trying the button. I don't get any errors but not does it work. I went to their example in Plunker, copied what it generated, and it displays right telling me I got the css in right, at least.
Including the webpack vendor configuration as a starting point, as this seems to be key because how it bundles the css and js.
TIA
Webpack.vendor
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const merge = require('webpack-merge');
const treeShakableModules = [
'#angular/animations',
'#angular/common',
'#angular/compiler',
'#angular/core',
'#angular/forms',
'#angular/http',
'#angular/platform-browser',
'#angular/platform-browser-dynamic',
'#angular/router',
'#angular/material',
'#angular/cdk',
'zone.js'
];
const nonTreeShakableModules = [
'bootstrap',
'jqwidgets-framework',
"#angular/material/prebuilt-themes/indigo-pink.css",
'bootstrap/dist/css/bootstrap.css',
'font-awesome/css/font-awesome.css',
'es6-promise',
'es6-shim',
'event-source-polyfill',
'jquery',
];
const allModules = treeShakableModules.concat(nonTreeShakableModules);
module.exports = (env) => {
const extractCSS = new ExtractTextPlugin('vendor.css');
const isDevBuild = !(env && env.prod);
const sharedConfig = {
stats: { modules: false },
resolve: { extensions: [ '.js' ] },
module: {
rules: [
{ test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-loader?limit=100000' }
]
},
output: {
publicPath: 'dist/',
filename: '[name].js',
library: '[name]_[hash]'
},
plugins: [
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
new webpack.ContextReplacementPlugin(/\#angular\b.*\b(bundles|linker)/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/11580
new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)#angular/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/14898
new webpack.IgnorePlugin(/^vertx$/) // Workaround for https://github.com/stefanpenner/es6-promise/issues/100
]
};
const clientBundleConfig = merge(sharedConfig, {
entry: {
// To keep development builds fast, include all vendor dependencies in the vendor bundle.
// But for production builds, leave the tree-shakable ones out so the AOT compiler can produce a smaller bundle.
vendor: isDevBuild ? allModules : nonTreeShakableModules
},
output: { path: path.join(__dirname, 'wwwroot', 'dist') },
module: {
rules: [
{ test: /\.css(\?|$)/, use: extractCSS.extract({ use: isDevBuild ? 'css-loader' : 'css-loader?minimize' }) }
]
},
plugins: [
extractCSS,
new webpack.DllPlugin({
path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
name: '[name]_[hash]'
})
].concat(isDevBuild ? [] : [
new webpack.optimize.UglifyJsPlugin()
])
});
const serverBundleConfig = merge(sharedConfig, {
target: 'node',
resolve: { mainFields: ['main'] },
entry: { vendor: allModules.concat(['aspnet-prerendering']) },
output: {
path: path.join(__dirname, 'ClientApp', 'dist'),
libraryTarget: 'commonjs2',
},
module: {
rules: [ { test: /\.css(\?|$)/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] } ]
},
plugins: [
new webpack.DllPlugin({
path: path.join(__dirname, 'ClientApp', 'dist', '[name]-manifest.json'),
name: '[name]_[hash]'
})
]
});
return [clientBundleConfig, serverBundleConfig];
}
You need to include angular material and cdk in nonTreeShakableModules like:
const treeShakableModules = [
'#angular/animations',
'#angular/common',
'#angular/compiler',
'#angular/core',
'#angular/forms',
'#angular/http',
'#angular/platform-browser',
'#angular/platform-browser-dynamic',
'#angular/router',
'zone.js',
];
const nonTreeShakableModules = [
'bootstrap',
'bootstrap/dist/css/bootstrap.css',
'#angular/material',
'#angular/material/prebuilt-themes/indigo-pink.css',
'#angular/cdk',
'es6-promise',
'es6-shim',
'event-source-polyfill',
'jquery',
];
Make sure you have installed both angular material and cdk modules from npm with the following 2 commands (animations module is optional):
npm install --save #angular/material #angular/cdk
npm install --save #angular/animations
This should add the following lines in package.json:
"#angular/animations": "https://registry.npmjs.org/#angular/animations/-/animations-4.2.5.tgz",
"#angular/cdk": "^2.0.0-beta.8",
"#angular/material": "^2.0.0-beta.8",
You now should try executing webpack build with following command in cmd or PowerShell:
webpack --config webpack.config.vendor.js
If there are no errors you can include the components you want to use in app.module.shared.ts:
// angular material modules
import {
MdAutocompleteModule,
MdButtonModule,
MdButtonToggleModule,
MdCardModule,
MdCheckboxModule,
MdChipsModule,
MdCoreModule,
MdDatepickerModule,
MdDialogModule,
MdExpansionModule,
MdGridListModule,
MdIconModule,
MdInputModule,
MdListModule,
MdMenuModule,
MdNativeDateModule,
MdPaginatorModule,
MdProgressBarModule,
MdProgressSpinnerModule,
MdRadioModule,
MdRippleModule,
MdSelectModule,
MdSidenavModule,
MdSliderModule,
MdSlideToggleModule,
MdSnackBarModule,
MdSortModule,
MdTableModule,
MdTabsModule,
MdToolbarModule,
MdTooltipModule,
} from '#angular/material';
import { CdkTableModule } from '#angular/cdk';
and add them to imports in #NgModule
There are still some components that are bugged until next fixes. Like the checkbox component which breaks server-side rendering when you refresh page. But it will be fixed in the next release (it has been already on master branch).
Using latest Angular Material in ASP.net Core 2.0 with default installed node packages is more difficult and time consuming for resolving package dependencies.
Use below version of angular material in package.json
"#angular/cdk": "^2.0.0-beta.12"
"#angular/material": "^2.0.0-beta.12"
followed by run below command to install it.
npm install --save

Resources