NUXT Duplicating Styles - vue.js

Within my NUXT project it seems that CSS is being duplicated, not only on individual components, but when compiled duplicates styles from my nuxt.config.js - styleResources -> scss into the head tag.
This seems to be a problem for me pre NUXT 2.0 as well as post (current ver: 2.8.1). I've tried a bunch of things on build but I must be missing something...
My config for the global styles:
module.exports = {
...
styleResources: {
scss: [
'~/styles/variables.scss',
'~/styles/normalize.scss',
'~/styles/forms.scss',
'~/styles/mixins.scss',
'~/styles/type.scss',
'~/styles/buttons.scss',
'~/styles/font.scss',
'~/styles/loader.scss'
],
},
build: {
path: '',
parallel: true,
cache: true,
optimization: {
minimize: true,
runtimeChunk: true,
concatenateModules: true,
splitChunks: {
chunks: 'all',
minSize: 30000,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 20,
maxInitialRequests: 3,
automaticNameDelimiter: '~',
name: true,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
},
// extractCSS: true,
optimizeCSS: true,
publicPath: process.env.CDN_URL || '',
/*
** Run ESLint on save
*/
extend (config, { isDev, isClient }) {
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
// loader: 'pug-plain-loader',
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
},
plugins: [
new webpack.ProvidePlugin({
mapboxgl: 'mapbox-gl'
})
]
}
...
}
!https://i.imgur.com/Uls5Kbl.png
!https://i.imgur.com/gcGR0La.png
The end goal is to obviously not have duplicate styles.

nuxt-styleResources module is only meant to share scss variables and mixins across your components. You shouldn't specify any styles there, use css field instead:
styleResources: {
scss: [
'~/styles/variables.scss',
'~/styles/mixins.scss',
],
},
css: [
'~/styles/normalize.scss',
'~/styles/forms.scss',
'~/styles/type.scss',
'~/styles/buttons.scss',
'~/styles/font.scss',
'~/styles/loader.scss'
]

Related

Vue SFC styles not being extracted in webpack production build

Trying to add vue (and SFCs) to my webpack app. The <template> and <script> blocks work fine, but for some reason the styles in the <style> block are not being extracted for production build.
In the dev build, it's extracting the .vue <style> block to a separate css file (named for the entrypoint). Which is OK but I'd prefer they went into my main stylesheet.
But no matter what I try, I can't get any .vue styles to show up (in any file) for the production build.
This is an abbreviated version of my webpack config:
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const VueLoaderPlugin = require("vue-loader/lib/plugin");
...
module.exports = (env) => {
return {
entry: {
app: ["./src/polyfills.js", "./src/scss/styles.scss", "./src/app.js"],
...
testview: "./src/js/views/TestView.js"
},
output: {
path: assets,
filename: "[name].[hash].js",
publicPath: "/static/"
},
resolve: {
modules: ["node_modules", "src"],
alias: {
vue$: "vue/dist/vue.esm.js"
},
extensions: ["*", ".js", ".vue"]
},
module: {
rules: [
{
test: /\.vue$/,
loader: "vue-loader"
},
{
test: /\.js?$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader",
options: {
presets: [
[
"#babel/preset-env",
{
targets: {
browsers: ["> 1%", "last 2 versions", "ie >= 11"]
}
}
]
],
plugins: ["#babel/plugin-proposal-class-properties"],
code: true,
comments: true,
cacheDirectory: true,
babelrc: false
}
}
]
},
{
test: /\.s?[ac]ss$/,
use: [
"vue-style-loader",
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
sourceMap: ifNotProduction()
}
},
{
loader: "postcss-loader",
options: {
ident: "postcss",
sourceMap: ifNotProduction(),
plugins: () =>
ifProduction([
require("autoprefixer")({
preset: "default"
}),
require("cssnano"),
require("css-mqpacker")
])
}
},
{
loader: "sass-loader",
options: {
sourceMap: ifNotProduction()
}
}
]
}
]
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
name: "commons",
chunks: "initial",
minChunks: 2,
minSize: 0
},
styles: {
name: "styles",
test: /\.css$/,
chunks: "all",
enforce: true
}
}
},
occurrenceOrder: true
},
plugins: [
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
filename: "style.[hash].css"
}),
new HtmlWebpackPlugin({
hash: true,
inject: false,
template: "./src/jinja-templates/base.html.j2",
filename: `${templates}/base.html.j2`,
})
]
};
};
The .vue file I'm using is this demo one. I'm trying to import it into the entrypoint called 'testview' which contains simply:
import Vue from "vue";
import MainContent from "../components/main-content";
let MainComponent = Vue.extend(MainContent);
new MainComponent().$mount("#mainContent");
Did figure it out. I had to remove sideEffects: false from my package.json. This issue explains it further.
Still would like to know how to extract the .vue styles to my main stylesheet As it is now, the .vue styles are extracting to a separate stylesheet (dev and production).

ESLint throw error Expected method shorthand (object shorthand)

I am following the steps in this tutorial :
https://www.youtube.com/watch?v=z6hQqgvGI4Y
using VSCode (version 1.22.2) as my editor
I am running the following version
==> vue --version
2.9.3
of Vue / vue-cli installed from npm using the steps outlined here :
npm install --global vue-cli
My VSCode workspace settings (User settings) are as follows :
{
"workbench.colorTheme": "Visual Studio Dark",
"window.zoomLevel": 1,
"workbench.statusBar.visible": true,
"workbench.startupEditor": "newUntitledFile",
// Format a file on save. A formatter must be available, the file must not be auto-saved, and editor must not be shutting down.
// "editor.formatOnSave": true,
"eslint.autoFixOnSave": true,
// Enable/disable default JavaScript formatter (For Prettier)
"javascript.format.enable": false,
// Use 'prettier-eslint' instead of 'prettier'. Other settings will only be fallbacks in case they could not be inferred from eslint rules.
"prettier.eslintIntegration": false,
"editor.insertSpaces": true,
"[javascript]": {
"editor.tabSize": 2,
"editor.insertSpaces": true
},
"[vue]": {
"editor.tabSize": 2,
"editor.insertSpaces": true
},
"eslint.options": {
"extensions": [".html", ".js", ".vue", ".jsx"]
},
"eslint.validate": [
{
"language": "html",
"autoFix": true
},
{
"language": "vue",
"autoFix": false
},
{
"language": "javascript",
"autoFix": true
},
{
"language": "javascriptreact",
"autoFix": true
}
]
}
I have the Vetur tooling for VSCode installed :
https://github.com/vuejs/vetur
I have the following files :
src/components/HomeCentral.vue
<template>
<div class="homecentral">
<input type="text" v-model="title"><br/>
<h1>{{title}}</h1>
<p v-if="showName">{{user.first_name}}</p>
<p v-else>Nobody</p>
<ul>
<li v-for="item in items" :key="item.id">{{item.title}}</li>
</ul>
<button v-on:click="greet('Hello World')">Say Greeting</button>
</div>
</template>
<script>
export default {
name: 'HomeCentral',
data() {
return {
title: 'Welcome',
user: {
first_name: 'John',
last_name: 'Doe',
},
showName: true,
items: [
{ title: 'Item One' },
{ title: 'Item Two' },
{ title: 'Item Three' },
],
};
},
methods: {
greet: function (greeting) {
alert(greeting);
},
},
};
</script>
<style scoped>
</style>
src/App.vue
<template>
<div id="app">
<home-central></home-central>
</div>
</template>
<script>
import HomeCentral from './components/HomeCentral';
export default {
name: 'App',
components: {
HomeCentral,
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
src/router/index.js
import Vue from 'vue';
import Router from 'vue-router';
import HomeCentral from '../components/HomeCentral';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'HomeCentral',
component: HomeCentral,
},
],
});
My .eslintrc looks as follows :
// https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
env: {
browser: true,
node: true,
"es6": false
},
extends: 'airbnb-base',
// required to lint *.vue files
plugins: [
'html',
'vue'
],
// check if imports actually resolve
settings: {
'import/resolver': {
webpack: {
config: 'build/webpack.base.conf.js'
}
}
},
// add your custom rules here
rules: {
// don't require .vue extension when importing
'import/extensions': ['error', 'always', {
js: 'never',
vue: 'never'
}],
// disallow reassignment of function parameters
// disallow parameter object manipulation except for specific exclusions
'no-param-reassign': ['error', {
props: true,
ignorePropertyModificationsFor: [
'state', // for vuex state
'acc', // for reduce accumulators
'e' // for e.returnvalue
]
}],
// allow optionalDependencies
'import/no-extraneous-dependencies': ['error', {
optionalDependencies: ['test/unit/index.js']
}],
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
}
My .editorconfig looks like this :
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
But when I run
==> npm run dev
I get the following output :
> webpack-dev-server --inline --progress --config build/webpack.dev.conf.js
95% emitting
WARNING Compiled with 1 warnings 3:01:35 PM
⚠ http://eslint.org/docs/rules/func-names Unexpected unnamed method 'greet'
src/components/HomeCentral.vue:33:12
greet: function (greeting) {
^
⚠ http://eslint.org/docs/rules/no-alert Unexpected alert
src/components/HomeCentral.vue:34:7
alert(greeting);
^
✘ http://eslint.org/docs/rules/object-shorthand Expected method shorthand
src/components/HomeCentral.vue:33:5
greet: function (greeting) {
^
✘ 3 problems (1 error, 2 warnings)
Errors:
1 http://eslint.org/docs/rules/object-shorthand
Warnings:
1 http://eslint.org/docs/rules/no-alert
1 http://eslint.org/docs/rules/func-names
You may use special comments to disable some warnings.
Use // eslint-disable-next-line to ignore the next line.
Use /* eslint-disable */ to ignore all warnings in a file.
Why is ESlint complaining about "Expected method shorthand" as an error and pointing to the following ES6 linting rule :
http://eslint.org/docs/rules/object-shorthand
Does 2.9.3 version of Vue use ES6 ?
How to silence the VScode editor from linting this semantically correct Vue code :
Fixed by following PeterVojtek answer at the following :
https://github.com/vuejs-templates/webpack/issues/73
Basically changed the following section on build/webpack.base.conf.js
const createLintingRule = () => ({
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter'),
emitWarning: !config.dev.showEslintErrorsInOverlay
}
})
to
const createLintingRule = () => ({
})
Also removed 'html' from plugins sections of .eslintrc.js
// https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
env: {
browser: true,
node: true,
"es6": false
},
extends: [
'airbnb-base',
],
// required to lint *.vue files
plugins: [
'vue',
],
// check if imports actually resolve
settings: {
'import/resolver': {
webpack: {
config: 'build/webpack.base.conf.js'
}
}
},
// add your custom rules here
rules: {
// don't require .vue extension when importing
'import/extensions': ['error', 'always', {
js: 'never',
vue: 'never'
}],
// disallow reassignment of function parameters
// disallow parameter object manipulation except for specific exclusions
'no-param-reassign': ['error', {
props: true,
ignorePropertyModificationsFor: [
'state', // for vuex state
'acc', // for reduce accumulators
'e' // for e.returnvalue
]
}],
// allow optionalDependencies
'import/no-extraneous-dependencies': ['error', {
optionalDependencies: ['test/unit/index.js']
}],
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
}
TSlint error/warning in callback function in 'Angular 10', VS code version 1.53.2 -
Solution -
doc.html(htmlData.innerHTML, {
callback(data: any): void {
data.save('angular-demo.pdf');
},
x: 10,
y: 10
});
package.json -
{
"dependencies": {
"#angular/core": "~10.1.3",
...
},
"devDependencies": {
"#angular/cli": "~10.1.3",
"#types/node": "^12.11.1",
"ts-node": "~8.3.0",
"tslint": "~6.1.0",
"typescript": "~4.0.2",
...
}
}

Sapper/Svelte SASS preprocessing?

So I was checking out the realworld implementation of Sapper/Svelte: https://github.com/sveltejs/realworld
I've read a lot about SASS preprocessing, and it doesn't seem like it is fully supported, but there are some docs on it. From what I could put together, I should be able to preprocess my tags after I made the following modifications to my webpack.client.config.js file:
const svelte = require('rollup-plugin-svelte');
const sass = require('svelte-preprocess-sass').sass;
const config = require('sapper/webpack/config.js');
const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
entry: config.client.entry(),
output: config.client.output(),
resolve: {
extensions: ['.js', '.html']
},
module: {
rules: [
{
test: /\.html$/,
exclude: /node_modules/,
use: {
loader: 'svelte-loader',
options: {
hydratable: true,
emitCss: !config.dev,
cascade: false,
store: true
}
}
},
config.dev && {
test: /\.css$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" }
]
},
!config.dev && {
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [{ loader: 'css-loader', options: { sourceMap: config.dev } }]
})
}
].filter(Boolean)
},
plugins: [
svelte({
preprocess: {
style: sass(),
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'main',
async: true,
children: true
}),
config.dev && new webpack.HotModuleReplacementPlugin(),
!config.dev && new ExtractTextPlugin('main.css'),
!config.dev && new webpack.optimize.ModuleConcatenationPlugin(),
!config.dev && new UglifyJSPlugin(),
].filter(Boolean),
devtool: config.dev ? 'inline-source-map' : false
};
I keep getting the following error:
node server.js
realworldsapper/node_modules/tapable/lib/Tapable.js:375
arguments[i].apply(this);
Any ideas on how to fix this?
You're mixing and matching Rollup and webpack, which are two different module bundlers — you're adding rollup-plugin-svelte to a webpack config, and webpack doesn't know what to do with it so it throws an error.
Instead, use svelte-preprocess-sass inside the svelte-loader config:
use: {
loader: 'svelte-loader',
options: {
hydratable: true,
emitCss: !config.dev,
cascade: false,
store: true,
style: sass()
}
}
(Note that the style: sass() line will become preprocess: { style: sass() } in a future version of svelte-loader — see this issue).
By the way, it looks like you're using an older version of Sapper — there have been some major improvements recently, so it's worth upgrading to 0.9. Unfortunately it does mean making some changes to your project structure (see the migration guide for the details, or reclone sapper-template and copy your routes folder over).
You should add exclude: /node_modules/ to each of your rules:
test: /\.css$/,
exclude: /node_modules/, // <- Add this
This ensures that transpilation is not applied to any of the files in the node_modules folder.

karma+webpack+typescript+mocha require is not defined

I try to configure my environment to run tests on node.
This my my webpack.config.test.js
const serverConfig = {
module: {
loaders: [
{test: /\.tsx?$/, loader: 'ts-loader' }
]
},
target: 'node',
externals:[nodeExternals()],
resolve: {
extensions: ['.ts', '.tsx', '.js']
}
};
module.exports = serverConfig;
karma.config.js
// Karma configuration
// Generated on Tue Jun 27 2017 07:20:43 GMT-0500 (Hora est. Pacífico, Sudamérica)
const webpackConfig=require('./config/webpack/webpack.test');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha','es6-shim'],
plugins:[
require("karma-es6-shim"),
'karma-webpack',
'karma-jsdom-launcher',
'karma-mocha',
'karma-spec-reporter',
'karma-jsdom-launcher',
'karma-coverage',
'karma-chrome-launcher',
"karma-phantomjs-launcher",
'karma-htmlfile-reporter'
],
files: [
'test/**/*.spec.ts'
],
coverageReporter: {
webpackMiddleware: {
stats: "errors-only"
},
dir: 'build/coverage/',
reporters: [
{ type: 'html' },
{ type: 'text' },
{ type: 'text-summary' }
]
},
// list of files to exclude
exclude: [
],
preprocessors: {
'test/**/*.spec.ts':["webpack","coverage"]
},
webpack:webpackConfig,
reporters: ['spec','progress','html'],
htmlReporter: {
outputFile: 'tests/units.html',
// Optional
pageTitle: 'Unit Tests',
subPageTitle: 'A sample project description',
groupSuites: true,
useCompactStyle: true,
useLegacyStyle: true
},
// web server port
port: 9876,
colors: true,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false,
concurrency: Infinity
})
}
test1
import { DBCONFIG } from './../src/config/db.config';
import { CONEXION } from './../src/config/database/mongo';
import { expect } from 'chai';
describe("#DATABASE",()=>{
it("Esta conectado",()=>{
CONEXION("hola",DBCONFIG.MONGO_URL_LOCAL)
.then(()=>{
expect(1).to.be("1");
})
.catch((e)=>{
expect(1).to.be(e);
})
})
});
test2
import { expect } from 'chai';
describe("#User",()=>{
it("use2r",()=>{
expect(1).to.equal("1");
})
})
When I run mocha + webpack with mocha-webpack, there is no problem the tests are running.
package.json
"test-server": "mocha-webpack --timeout 1000 --webpack-config config/webpack/webpack.test.js test/**/*.spec.ts",
"test":"karma start"
When I do it from karma depending on which browser I use to display the messages I throw similar errors, when I throw it with jsdom or PhantomJS I throw the following
require is not defined o Cannot find
Looking in git, the only answer that solved the problem, is to put in the processors of karma the following.
'test/**/*.spec.ts':["webpack","coverage"]
It is the same way and I have varied, but the error continues.

how to use webpack split common business code?

I use webpack.optimize.CommonsChunkPlugin to Generate an extra chunk(vueCommon.js) which contains vuejs、vue-router、vue-resource...;but I want to Generate another business commonChunk like util.js。they are used just in some pages by "import ajax from '../service/service.js'";
problems after build:
every generated page.js has the code of service.js。
brief demos:
https://github.com/wxungang/vueJs
//webpack.base.js
"use strict";
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
const CONFIG = require('./config');
var projectRoot = CONFIG.projectRoot || path.resolve(__dirname, '../');
var _ENV = CONFIG.env || 'dev';//prod
module.exports = {
devtool: _ENV != 'prod' ? '#eval-source-map' : false,
context: __dirname,//http://wxungang.github.io/1104/vue
entry: {
app: path.join(projectRoot, './vue/app.js'),
page: path.join(projectRoot, './vue/page.js')
},
output: {
path: path.join(projectRoot, './build/vue-' + _ENV),
publicPath: '',//'./build/vue-'+_ENV+'/',//path.join(__dirname, '../src/build/dev/')
filename: '[name].js',
chunkFilename: 'chunks/[name].chunk.js',
// crossOriginLoading: 'anonymous'
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.common.js',
'vue-router$': 'vue-router/dist/vue-router.common.js'
},
modules: ["node_modules"],
mainFiles: ["index", "app"],
extensions: [".js", ".json", '.vue']
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
// Since sass-loader (weirdly) has SCSS as its default parse mode, we map
// the "scss" and "sass" values for the lang attribute to the right configs here.
// other preprocessors should work out of the box, no loader config like this nessessary.
'scss': 'vue-style-loader!css-loader!sass-loader',
'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax',
'less': 'vue-style-loader!css-loader!less-loader'
}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.less$/,
loader: "style-loader!css-loader!less-loader"
},
{
test: /\.scss$/,
loaders: ["style-loader", "css-loader", "sass-loader"]
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.html$/,
loader: 'vue-html-loader'
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
plugins: [
//注入一些全局变量
new webpack.DefinePlugin({
_ENV_: _ENV,
_VERSION_: JSON.stringify("1.0.0")
}),
new webpack.optimize.CommonsChunkPlugin({
name: "commons",
// (the commons chunk name)
filename: "vueCommons.js",
// (the filename of the commons chunk)
// minChunks: 2,
// (Modules must be shared between 3 entries)
// chunks: ["pageA", "pageB"],
// (Only use these entries)
// children: true,
// async: true,
}),
//可以和entry文件联合配置
new HtmlWebpackPlugin({
inject: false,
title: 'vueJs of app',
filename: 'app.html',
template: '../vue/entry/template.ejs',
scripts: ['./vueCommons.js', './app.js']
}),
new HtmlWebpackPlugin({
inject: false,
title: 'vueJs of page',
filename: 'page.html',
template: '../vue/entry/template.ejs',
scripts: ['./vueCommons.js', './page.js']
})
]
};
How did you use CommonsChunkPlugin to generate vueCommon.js?
A simple way is to add a new wepack entry like
utils: ['../service/service.js']
then add a new CommonsChunkPlugin instance in the webpack plugins array like this
new webpack.optimize.CommonsChunkPlugin('utils'),
the CommonsChunkPlugin will do the work by remove all utils module in other chunk files and generate only one utils.js.
Or you can just set minChunks option of the existing CommonsChunkPlugin into a number to wrap the vue file and utils together.