Custom webpack configuration - laravel

I'm using Laravel 5.6 and I would like to add the vtk.js dependency.
I'm using the basic configuration of webpack included by laravel-mix. I'm creating my default app.js and don't want to change this behaviour. So vtk should be included in the app.js.
I also saw that we can add a custom webpack config like this
mix.webpackConfig({
resolve: {
modules: [
path.resolve(__dirname, 'node_modules'),
]
}
});
But I realy don't know how to include the module.exports and module from the webpack of js in the mix of laravel...

You have to append the path your js file in your webpack
run npm dev

const path = require('path');
const webpack = require('webpack');
const vtkRules = require('vtk.js/Utilities/config/dependency.js').webpack.v2.rules;
mix.webpackConfig({
module: {
rules: [...vtkRules]
},
resolve: {
modules: [
path.resolve(__dirname, 'node_modules'),
]
}
});
I'm not used to VTK, you have to import/configure everything else on your app.js, which is your entrypoint.

Related

CSS isn't working in production environment with Laravel Mix 5

This is for my Laravel + Vue SPA app.
I have this Laravel Mix config file here:
const path = require('path');
const fs = require('fs-extra');
const mix = require('laravel-mix');
const tailwindcss = require('tailwindcss');
require('laravel-mix-bundle-analyzer');
function publishAssets() {
const publicDir = path.resolve(__dirname, './public');
if (mix.inProduction()) {
fs.removeSync(path.join(publicDir, 'dist'));
}
fs.copySync(path.join(publicDir, 'build', 'dist'), path.join(publicDir, 'dist'));
fs.removeSync(path.join(publicDir, 'build'));
}
mix.js('resources/js/app.js', 'public/dist/js')
.sass('resources/sass/app.scss', 'public/dist/css').options({
postCss: [tailwindcss('./tailwind.config.js')],
processCssUrls: false,
});
// alias the ~/resources folder
mix.webpackConfig({
plugins: [
// new BundleAnalyzerPlugin()
],
resolve: {
extensions: ['.js', '.json', '.vue'],
alias: {
'#': `${__dirname}/resources`,
'~': path.join(__dirname, './resources/js'),
ziggy: path.join(__dirname, './vendor/tightenco/ziggy/dist/js/route.js'),
},
},
output: {
chunkFilename: 'dist/js/[chunkhash].js',
path: mix.config.hmr ? '/' : path.resolve(__dirname, './public/build'),
},
});
mix.then(() => {
if (!mix.config.hmr) {
process.nextTick(() => publishAssets());
}
});
It works fine with npm run watch, but when I do npm run production, the CSS doesn't work. The site loads and works, but the CSS is missing.
Can anyone see what in my code is causing it?
Here's my spa.blade.php:
<link rel="stylesheet" href="{{ mix('dist/css/app.css') }}">
...
<script src="{{ mix('dist/js/app.js') }}"></script>
In the network tab of Chrome dev tools, the CSS file is 270kb in develop environment and 42kb in prod environment.
Something is getting translated wrong.
In my case, it cause by setting wrong property "purge" in tailwindcss config file.
When I ran "npm run hot" or "npm run dev", the website was fine.
But it broke when I ran "npm run prod".
It seems the dev mode ignore the property "purge".
I'm calling this solved for now because my site started working.
it was extremely difficult to navigate since I had 6 months of work on a dev branch, and it worked via npm run watch. When I merged into master, npm run production loaded incorrectly--the styles were half there and half missing.
The solution was to downgrade from tailwindcss#1.9 to tailwindcss#1.4.
Along my way, I read something about postcss or something not working with the --no-progress flag which is on npm run production.
A person could try removing that flag, but I already downgraded tailwind so I didn't try that.

Gatsby Develop Failing using gatsby-plugin-sass

After installing the gatsby-plugin-sass module:
When I try to run gatsby build, I get the following error:
ERROR
Unknown error from PostCSS plugin. Your current PostCSS version is 6.0.23, but autoprefixer uses 7.0.26. Perhaps this is the source of the error below.
ERROR #98123 WEBPACK
Generating development JavaScript bundle failed
Browser queries must be an array or string. Got object.
File: src/indexs.sass
failed Building development bundle - 9.200s
I have been working on a resolution to this for hours. I have tried:
custom webpack rules in gatsby-node.js for sass files
reading, re-reading, and re-re-reading the instruction on gatsby's site
updating PostCSS using npm in every way I know how
So far, nothing has worked.
Why is it so complicated to get sass working with gatsby? When the documentation on gatsby's site makes it seem so easy?
Any suggestions what I can do to get this working?
in gatsby-node.js:
exports.onCreateWebpackConfig = ({
stage,
rules,
loaders,
plugins,
actions,
}) => {
// console.log('rules',rules)
// console.log('rules.css',rules.css())
// console.log('rules',rules.postcss())
actions.setWebpackConfig({
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
],
},
plugins: [
plugins.define({
__DEVELOPMENT__: stage === `develop` || stage === `develop-html`,
}),
],
})
}
In gatsby-config.js:
{
resolve: `gatsby-plugin-postcss`,
options: {
postCssPlugins: [require(`postcss-preset-env`)({ stage: 0 })],
},
},
`gatsby-plugin-sass`,
the sass import line in gatsby-browser.js:
import "./src/indexs.sass"
Using sass instead of node-sass saved my day.
remove node-sass
npm uninstall node-sass
or
yarn remove node-sass
and add sass aka dart-sass
npm install --save-dev sass
or
yarn add sass
then edit gatsby-config.js
plugins: [
{
resolve: `gatsby-plugin-sass`,
options: {
implementation: require("sass"),
},
},
]
now run gatsby develop
:)
I'm a bit late to the party but hopefully this might help someone.
I have Sass setup and working with Gatsby without to much extra config required.
Install both node-sass and gatsby-plugin-sass via npm.
npm install --save node-sass gatsby-plugin-sass
Include gatsby-plugin-sass in your gatsby-config.js file in plugins: [] as below with any other Gatsby plugins you maybe using.
module.exports = {
siteMetadata: {
title: `#`,
description: `#`,
author: `#`,
},
plugins: [
`gatsby-plugin-sass`,
],
}
Write your styles as .sass or .scss files and import your main styles.scss (or whatever you prefer to name it) either in your main Layout.js file or gatsby-browser.js file as below using the path to the location of your styles.scss file.
import "./src/styles/styles.scss"
I hope this works for you but if you have any other trouble add a comment and I'll try to reply back.
I hope someone chimes in on this to show how exactly to set up gatsbys sass plugin. I could not get it to work at all.
But I did find a workaround in my case:
I removed gatsby-plugin-sass from the plugins array in gatsby-config.js, turning it off (but I did not uninstall it using npm)
I installed postcss-node-sass and postcss
I added this info to the plugins array in gatsby-config.js:
{
resolve: `gatsby-plugin-postcss`,
options: {
postCssPlugins: [
require(`postcss-preset-env`)({ stage: 0 }),
require(`postcss-node-sass`)(),
],
},
},
I added a custom rule for webpack in gatsby-node.js:
exports.onCreateWebpackConfig = ({
stage,
rules,
loaders,
plugins,
actions,
}) => {
// console.log('rules',rules)
// console.log('rules.css',rules.css())
// console.log('rules',rules.postcss())
actions.setWebpackConfig({
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
],
},
plugins: [
plugins.define({
__DEVELOPMENT__: stage === `develop` || stage === `develop-html`,
}),
],
})
}

Issue with with custom webpack configuration

Laravel Mix (4.0.15)
OS Ubuntu 18.04
Steps to Reproduce:
Create a New laravel project (Laravel 5.8, as it uses laravel-mix 4)
Import a component dynamically.
Vue.component('example', () => import('./components/Example.vue'));
I have been using babel dynamic import to import this.
"#babel/plugin-syntax-dynamic-import": "^7.2.0",
You may need .babelrc in the root.
try to put the chunks file into public/js/prod It works file till now.
let mix = require('laravel-mix');
mix.webpackConfig({
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
// 'vue$': 'vue/dist/vue.esm.js',
'#': __dirname + '/resources/assets/js'
},
},
output: {
chunkFilename: 'js/prod/[name].js',
},
});
mix.js('resources/assets/js/app.js', 'js')
.version();
try to extract the plugins, & It causes problem.
mix.js('resources/assets/js/app.js', 'js')
.mix.extract(['vue','jquery', 'popper.js'])
.version();
Now the file app.js and vendor.js goes to js/prod//js/app.js and js/prod//js/vendor.js respectively.
There is no way to put the app.js and vendor.js in /js and chunks in /js/prod. In the previous version which was available.

Error when combining sass-loader with css-modules

I'm getting the following error when using SASS's map-get.
ERROR in ./src/special.scss
Module build failed: ModuleBuildError: Module build failed: Unknown word (11:14)
9 |
10 | #mixin mediaquery($name) {
> 11 | #media #{map-get($breakpoints, $name)} {
| ^
12 | #content;
13 | }
14 | }
This is only happening when I use both the sass-loader and another loader.
I first thought this was caused by the PostCSS Loader, but it seems like it's the sass-loading causing problems and not transforming the scss when using css-modules.
I've created a sample repo illustrating the problem: https://github.com/tiemevanveen/sass-css-components-fail-example.
You can use the different branches to test:
master: CSS Modules + SASS
postcss CSS Modules + SASS + PostCSS
log-source: Uses CSS modules + SASS + Custom source logging module
no-css-modules: SASS + Custom source logging module
Only the first and the last branch run without errors.
I've created the log-source example to see what the sass-loader is returning and it looks like it's not transforming the sass (but this might also be me misinterpreting how the loaders work).
The other example without css modules does show the right transformed code..
I'm puzzled why the master branch (without postcss or another custom loader) is working fine though.. if something would be wrong with the sass-loader then that one should also fail right?
I've filed an issue, but I'm thinking this has more chance on StackOverflow since it's such a specific problem and might be more a config problem. Here's my webpack config:
const webpack = require('webpack');
const path = require('path');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const WriteFilePlugin = require('write-file-webpack-plugin');
module.exports = {
devtool: 'source-source-map',
debug: true,
context: path.resolve(__dirname, './src'),
entry: {
app: './index.js'
},
output: {
path: path.resolve(__dirname, './static'),
filename: '[name].js',
publicPath: '/static/'
},
devServer: {
outputPath: path.resolve(__dirname, './static'),
},
plugins: [
new webpack.NoErrorsPlugin(),
new ExtractTextPlugin('[name].css'),
new WriteFilePlugin()
],
module: {
loaders: [
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', [
'css?modules&importLoaders=1&localIdentName=[path]_[name]_[local]',
// 'postcss-loader',
'sass'
])
},
// + js loader
]
},
postcss: [
autoprefixer({ browsers: ['> 0.5%'] })
],
resolveLoader: {
fallback: [
path.resolve(__dirname, 'loaders'),
path.join(process.cwd(), 'node_modules')
]
},
resolve: {
extensions: ['', '.js', '.json'],
}
};
You need to increase the importLoaders query parameter as you add loaders. That feature is poorly documented and confusing, but in your samples repo, importLoaders=2 with both Sass and PostCSS works.

using d3.js as an external in webpack

I'm using this tutorial to setup a React.js project with webpack. The webpack.config.js below is almost an exact copy (except that I'm using an app and 'dist' folder), and I am also adding d3.js as an external. Because React is added as an external it lets me do require('react') in any of my app files without including it in the bundle. I wish to do the same with d3.js and have installed it as a node_module, and listed it in the externals area of my webpack config, but when I do require('d3') i get an error message that it's not available.
How can I use d3 (or jQuery for that matter) as an external if I have it installed as a node_module?
this is my project setup
/app
/dist
/node_modules
package.json
webpack.config.js
module.exports = {
entry: './app/index.jsx',
output: {
path: './dist',
filename: 'bundle.js', //this is the default name, so you can skip it
//at this directory our bundle file will be available
//make sure port 8090 is used when launching webpack-dev-server
publicPath: 'http://localhost:8090/assets'
},
module: {
loaders: [
{
//tell webpack to use jsx-loader for all *.jsx files
test: /\.jsx$/,
loader: 'jsx-loader?insertPragma=React.DOM&harmony'
}
]
},
externals: {
//don't bundle the 'react' npm package with our bundle.js
//but get it from a global 'React' variable
'react': 'React',
'd3': 'd3'
},
resolve: {
modulesDirectories: ['app', 'node_modules'],
extensions: ['', '.js', '.jsx']
}
}
I know this question has been open a while, but hopefully this answer is still useful!
If you have installed d3 (or jQuery) as a node_module, you can use the webpack ProvidePlugin to tie an arbitrary key to a module.
The key will be then be available to require anywhere in your webpack app.
E.g. webpack.config.js
{
...lots of webpack config here...
...
plugins: [
new webpack.ProvidePlugin({
d3: 'd3',
$: 'jquery'
})
]
...
}
Then in my-file.js
var d3 = require('d3')
Hope that helps!

Resources