Webpack 2 - Problems parsing node_module - node.js

I'm unit testing with mocha-webpack v1.0.1, node v6.10. However, I'm getting an error from one of our node modules, where webpack couldn't parse a #. This is an internal library that we use that runs fine in another development environment. So, I'm confused why this is happening since you would think that a library in your node_module would be sort of self-sustaining and would know how to parse itself (and is validated as working in another environment).
Error in ./~/abc-components/src/abc-theme/index.scss
Module parse failed: /path/to/app/node_modules/abc-components/src/abc-theme/index.scss Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
| #charset "UTF-8";
| #import "abc-variables";
| #import "alert";
I believe # is an alias we use for resolving the module path in that library. I've modeled my setup after this tutorial.
From package.json:
"unit": "BABEL_ENV=test mocha-webpack --webpack-config build/webpack.test.conf.js --require test/unit/.setup src/**/*.spec.js --recursive --watch"
From build/webpack.test.conf.js config, including some comments of things I've tried:
var path = require('path')
var webpack = require('webpack')
var utils = require('./utils')
var config = require('../config')
// var nodeExternals = require('webpack-node-externals');
function resolve(dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
app: './src/main.js'
},
resolve: {
modules: [path.resolve('./src'), "node_modules"],
extensions: ['.js', '.vue', '.json', '.ts'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': resolve('src')
}
},
// externals: [nodeExternals()],
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
// plugins: [
// new webpack.optimize.CommonsChunkPlugin({
// name: "vendor",
// filename: "vendor.js",
// minChunks: function (module) {
// // This prevents stylesheet resources with the .css or .scss extension
// // from being moved from their original chunk to the vendor chunk
// if(module.resource && (/^.*\.(css|scss)$/).test(module.resource)) {
// return false;
// }
// return module.context && module.context.indexOf("node_modules") !== -1;
// }
// }),
// new webpack.DefinePlugin({
// 'process.env': require('../config/test.env')
// })
// ],
module: {
loaders: [
{
test: /\.(js|vue)$/,
// loader: 'eslint-loader',
// enforce: 'pre',
include: [resolve('src'), resolve('test'), resolve('node_modules')],
/* options: {
formatter: require('eslint-friendly-formatter')
} */
},
{
test: /\.pug$/,
loader: 'pug-loader'
},
{
test: /\.vue$/,
loader: 'vue-loader'
// options: vueLoaderConfig
},
{
test: /\.ts$/,
loader: "awesome-typescript-loader",
include: [resolve('src'), resolve('test')]
},
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['es2015']
},
include: [resolve('src'), resolve('test')]
// exclude: /node_modules/
},
{
test: /\.(mp3|wav)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('audio/[name].[hash:7].[ext]')
}
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
resolveLoader: {
alias: {
// necessary to to make lang="scss" work in test when using vue-loader's ?inject option
// see discussion at https://github.com/vuejs/vue-loader/issues/724
'scss-loader': 'sass-loader'
}
}
}

Include following config in loader.
module: {
loaders: [
{
test: /\.(scss|sass)$/i,
include: [
path.resolve(__dirname, 'node_modules'),
path.resolve(__dirname, 'path/to/imported/file/dir'), <== This solved the issue
],
loaders: ["css", "sass"]
},
]
},

Related

Module not found: Error: Can't resolve in webpack.common.js

when I do npm run build I am getting below error
ERROR in ./src/assets/scss/theme.scss
(./node_modules/css-loader/dist/cjs.js!./node_modules/resolve-url-loader!./node_modules/sass-loader/dist/cjs.js!./src/assets/scss/theme.scss)
Module not found: Error: Can't resolve
'../../../../fonts/materialdesignicons-webfont.woff?v=4.4.95' in
'D:\Work\BBYN\external\src\assets\scss' #
./src/assets/scss/theme.scss
(./node_modules/css-loader/dist/cjs.js!./node_modules/resolve-url-loader!./node_modules/sass-loader/dist/cjs.js!./src/assets/scss/theme.scss)
7:36-106 # ./src/assets/scss/theme.scss #
./src/extensions/masterApplicationCustomizer/MasterApplicationCustomizerApplicationCustomizer.ts
but If I run npm run watch it works properly
My webpack.commom.js is as below
const path = require('path')
const merge = require('webpack-merge')
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin')
const SetPublicPathPlugin = require('#rushstack/set-webpack-public-path-plugin').SetPublicPathPlugin
module.exports = merge({
target: 'web',
entry: {
'profile-web-part': path.join(__dirname, '../src/webparts/profile/ProfileWebPart.ts'),
'master-application-customizer-application-customizer': path.join(
__dirname,
'../src/extensions/masterApplicationCustomizer/MasterApplicationCustomizerApplicationCustomizer.ts'
),
'list-data-web-part': path.join(__dirname, '../src/webparts/listData/ListDataWebPart.ts')
},
output: {
path: path.join(__dirname, '../dist'),
filename: '[name].js',
libraryTarget: 'umd',
library: '[name]'
},
performance: {
hints: false
},
stats: {
errors: true,
colors: true,
chunks: false,
modules: false,
assets: false
},
externals: [/^#microsoft\//, 'ProfileWebPartStrings', 'ControlStrings', 'MasterApplicationCustomizerApplicationCustomizerStrings', 'ListDataWebPartStrings'],
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
options: {
transpileOnly: true
},
exclude: /node_modules/
},
{
test: /\.(jpg|png|woff|woff2|eot|ttf|svg|gif|dds)$/,
use: [
{
loader: '#microsoft/loader-cased-file',
options: {
name: '[name:lower]_[hash].[ext]'
}
}
]
},
{
test: /\.css$/,
use: [
{
loader: '#microsoft/loader-load-themed-styles',
options: {
async: true
}
},
{
loader: 'css-loader'
}
]
},
{
test: function (fileName) {
return fileName.endsWith('.module.scss') // scss modules support
},
use: [
{
loader: '#microsoft/loader-load-themed-styles',
options: {
async: true
}
},
'css-modules-typescript-loader',
{
loader: 'css-loader',
options: {
modules: true
}
}, // translates CSS into CommonJS
'sass-loader' // compiles Sass to CSS, using Node Sass by default
]
},
{
test: function (fileName) {
return !fileName.endsWith('.module.scss') && fileName.endsWith('.scss') // just regular .scss
},
use: [
{
loader: '#microsoft/loader-load-themed-styles',
options: {
async: true
}
},
'css-loader', // translates CSS into CommonJS
{
loader: 'resolve-url-loader'
},
'sass-loader' // compiles Sass to CSS, using Node Sass by default
]
}
]
},
resolve: {
extensions: ['.ts', '.tsx', '.js']
},
plugins: [
new ForkTsCheckerWebpackPlugin({
tslint: true
}),
new SetPublicPathPlugin({
scriptName: {
name: '[name]_?[a-zA-Z0-9-_]*.js',
isTokenized: true
}
})
]
})
I could solve the issue by using resolve-url-loader module. It can help to somebody Below is part of webpack.js
{
test: function (fileName) {
return !fileName.endsWith('.module.scss') && fileName.endsWith('.scss') // just regular .scss
},
use: [
{
loader: '#microsoft/loader-load-themed-styles',
options: {
async: true
}
},
{
loader: 'css-loader',
options: {
sourceMap: true
}
}, // translates CSS into CommonJS
'resolve-url-loader',
{
loader: 'sass-loader',
options: {
sourceMap: true
}
} // compiles Sass to CSS, using Node Sass by default
]
}
]

asset_url_for() returns None in flask cookie cutter (flask-webpack)

Im new to webpack. Im using flask-cookie-cutter which in turn uses Flask-Webpack
Im having issues in that App wont find my images in development.
Images are in assets/img folder
Ive tried using {{ asset_url_for('img/img_name.png') }} and various variations of it - and it just returns none.
Ive tried the usual flask way of {{ url_for('static', filename='img/img_name.png') }}
But I cant seem to access them.
const path = require('path');
const webpack = require('webpack');
/*
* Webpack Plugins
*/
const ManifestRevisionPlugin = require('manifest-revision-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// take debug mode from the environment
const debug = (process.env.NODE_ENV !== 'production');
// Development asset host (webpack dev server)
const publicHost = debug ? 'http://0.0.0.0:2992' : '';
const rootAssetPath = path.join(__dirname, 'assets');
module.exports = {
// configuration
context: __dirname,
entry: {
main_js: './assets/js/main',
main_css: [
path.join(__dirname, 'node_modules', 'materialize-css', 'dist', 'css', 'materialize.css'),
path.join(__dirname, 'assets', 'css', 'style.css'),
],
},
output: {
path: path.join(__dirname, 'dsi_website', 'static', 'build'),
publicPath: `${publicHost}/static/build/`,
filename: '[name].[hash].js',
chunkFilename: '[id].[hash].js',
},
resolve: {
extensions: ['.js', '.jsx', '.css'],
},
devtool: 'source-map',
devServer: {
headers: { 'Access-Control-Allow-Origin': '*' },
},
module: {
rules: [
{
test: /\.less$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: debug,
},
},
'css-loader!less-loader',
],
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: debug,
},
},
'css-loader',
],
},
{
test: /\.html$/,
loader: 'raw-loader'
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff'
}
},
{
test: /\.(ttf|eot|svg|png|jpe?g|gif|ico)(\?.*)?$/i,
loader: `file-loader?context=${rootAssetPath}&name=[path][name].[hash].[ext]`
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['env'],
cacheDirectory: true
}
},
],
},
plugins: [
new MiniCssExtractPlugin({ filename: '[name].[hash].css', }),
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }),
new ManifestRevisionPlugin(path.join(__dirname, 'dsi_website', 'webpack', 'manifest.json'), {
rootAssetPath,
ignorePaths: ['/js', '/css'],
}),
].concat(debug ? [] : [
// production webpack plugins go here
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
}
}),
]),
};
I was the same problem with flask-cookie-cutter and solve it by update/upgrade npm and add extensionsRegex: /\.(jpe?g|png|gif|svg)$/i at down file: webpack.config.js like this:
ManifestRevisionPlugin(path.join(__dirname, '<your app>', 'webpack', 'manifest.json'), {
rootAssetPath,
ignorePaths: ['/js', '/css'],
extensionsRegex: /\.(jpe?g|png|gif|svg)$/i
}),
source solution. Proper call to show image in temaplate:
{{ asset_url_for('img/img_name.png') }}
after that i check startup screen and i see that all my images load properly
[WEBPACK] _/assets/img/image_name.20aed528d50316c91ffedb5ba47b8c74.jpg 18.9 KiB [emitted]

configure webpack to load .vue files in node_modules

I would like to require .vue files from within my node_modules folder but it seems that webpack and | or the .vue loader doesn't transform this files.
This is my configuration right now:
const path = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const { VueLoaderPlugin } = require('vue-loader')
const isProd = process.env.NODE_ENV === 'production'
module.exports = {
devtool: isProd
? false
: '#cheap-module-source-map',
output: {
path: path.resolve(__dirname, '../dist'),
publicPath: '/dist/',
filename: '[name].[chunkhash].js'
},
resolve: {
alias: {
'public': path.resolve(__dirname, '../public')
}
},
module: {
noParse: /es6-promise\.js$/, // avoid webpack shimming process
rules: [
{
test: /\.pug$/,
loader: 'pug-plain-loader'
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
compilerOptions: {
preserveWhitespace: false
}
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'url-loader',
options: {
limit: 10000,
name: '[name].[ext]?[hash]'
}
},
{
test: /\.styl(us)?$/,
use: isProd
? ExtractTextPlugin.extract({
use: [
{
loader: 'css-loader',
options: { minimize: true }
},
'stylus-loader'
],
fallback: 'vue-style-loader'
})
: ['vue-style-loader', 'css-loader', 'stylus-loader']
},
]
},
performance: {
maxEntrypointSize: 300000,
hints: isProd ? 'warning' : false
},
plugins: isProd
? [
new VueLoaderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false, drop_console:true }
}),
new webpack.optimize.ModuleConcatenationPlugin(),
new ExtractTextPlugin({
filename: 'common.[chunkhash].css'
})
]
: [
new VueLoaderPlugin(),
new FriendlyErrorsPlugin()
]
}
I tried to set
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules\/(?!(my_components_folder)\/).*/
}
but without success.
I'm always getting the error:
(function (exports, require, module, __filename, __dirname) { <template lang="pug">
^
SyntaxError: Unexpected token <
How can I configure webpack to also transform files from within the node_modules folder?
I'm using webpack#3.8.1

Webpack 2 - Error in 'Debug'

Upgrading from web pack 1 to web pack 2. Error when running...
WebpackOptionsValidationError: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration has an unknown property 'debug'. These properties are valid:
I have included my code for web pack.config.js file.
Any help regarding this issue is much appreciated.
'use strict';
/**
* Module dependencies
*/
var path = require('path'),
webpack = require('webpack'),
HtmlWebpackPlugin = require('html-webpack-plugin'),
minimist = require('minimist'),
ngAnnotatePlugin = require('ng-annotate-webpack-plugin');
var argv = minimist(process.argv.slice(2));
var DEBUG = !argv.release;
var STYLE_LOADER = 'style-loader';
var CSS_LOADER = DEBUG ? 'css-loader' : 'css-loader?minimize';
var GLOBALS = {
'process.env.NODE_ENV': DEBUG ? '"development"' : '"production"',
'__DEV__': DEBUG
};
module.exports = {
output: {
path: path.join(__dirname, 'www'),
filename: '[name].js',
chunkFilename: '[chunkhash].js'
},
devtool: 'source-map',
cache: DEBUG,
debug: DEBUG,
stats: {
colors: true,
reasons: DEBUG
},
entry: {
app: ['./app/index.js']
},
module: {
//preLoaders: [{
// test: /\.js$/,
// exclude: /node_modules|dist|www|build/,
// loader: 'eslint-loader'
//}],
rules: [{
test: /\.css$/,
loader: 'style-loader!css-loader'
}, {
test: /\.html$/,
loader: 'html'
}, {
test: /\.json$/,
loader: 'json'
}, {
test: /\.scss$/,
loader: 'style!css!sass'
}, {
test: /\.(woff|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url?prefix=font/&limit=10000&name=font/[hash].[ext]'
}, {
test: /[\/]angular\.js$/,
loader: 'exports?angular'
}, {
test: /[\/]ionic\.js$/,
loader: 'exports?ionic'
}, {
test: /.*\.(gif|png|jpe?g)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=img/[hash].[ext]',
'image-webpack?{progressive:true, optimizationLevel:1, interlaced: false, pngquant:{quality: "65-90", speed: 4}}'
]
//' + DEBUG ? '1' : '7' + '
}]
},
resolve: {
modules: [
'node_modules'
],
alias: {}
},
plugins: [
new HtmlWebpackPlugin({
pkg: require('./package.json'),
template: 'app/entry-template.html'
}),
new ngAnnotatePlugin({
add: true
})
// new webpack.optimize.DedupePlugin(),
// new webpack.optimize.UglifyJsPlugin()
// new webpack.BannerPlugin(banner, options),
// new webpack.optimize.DedupePlugin()
]
};
Here is a migration guide, look for the debug property it states that it has moved under the loaderoptionsplugin
plugins: [ new webpack.LoaderOptionsPlugin({ debug: true }) ]
https://webpack.js.org/guides/migrating/
Side note: if you are migrating to version 2, why not upgrade to version 4?

Webpack not including ProvidePlugins

I have a small trial web application that I'm working on that uses the vue webpack template (https://github.com/vuejs-templates/webpack). I'm pretty new to webpack so I was assuming that I could add in to plugins a new webpack.ProvidePlugin and it would be available globally but when I do a npm run dev I get the following error:
/var/www/public/leadsStatsDashboard/liveleadstats/src/components/Hello.vue
18:17 error 'd3' is not defined no-undef
Which sounds like to me that it can't find the d3 reference. I'm no sure if there's some configuration I skipped over or what but any help would be appreciated. Here is the source for my files
Webpack.dev.conf.js:
var path = require('path')
var config = require('../config')
var utils = require('./utils')
var webpack = require('webpack')
var projectRoot = path.resolve(__dirname, '../')
module.exports = {
plugins: [
new webpack.ProvidePlugin({
d3: 'd3',
crossfilter: 'crossfilter',
dc: 'dc'
})
],
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
publicPath: config.build.assetsPublicPath,
filename: '[name].js'
},
resolve: {
extensions: ['', '.js', '.vue'],
fallback: [path.join(__dirname, '../node_modules')],
alias: {
'src': path.resolve(__dirname, '../src'),
'assets': path.resolve(__dirname, '../src/assets'),
'components': path.resolve(__dirname, '../src/components'),
'd3': path.resolve(__dirname, '../bower_components/d3/d3.min.js'),
'crossfilter': path.resolve(__dirname, '../bower_components/crossfilter/crossfilter.min.js'),
'dc': path.resolve(__dirname, '../bower_components/dcjs/dc.js')
}
},
resolveLoader: {
fallback: [path.join(__dirname, '../node_modules')]
},
module: {
preLoaders: [
{
test: /\.vue$/,
loader: 'eslint',
include: projectRoot,
exclude: /node_modules/
},
{
test: /\.js$/,
loader: 'eslint',
include: projectRoot,
exclude: /node_modules/
}
],
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /\.js$/,
loader: 'babel',
include: projectRoot,
exclude: /node_modules/
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.html$/,
loader: 'vue-html'
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url',
query: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url',
query: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
eslint: {
formatter: require('eslint-friendly-formatter')
},
vue: {
loaders: utils.cssLoaders()
}
}
Hello.vue
<template>
<div id="pieChartContainer">
</div>
</template>
<script>
export default {
data () {
return {
// note: changing this line won't causes changes
// with hot-reload because the reloaded component
// preserves its current state and we are modifying
// its initial state.
msg: 'Hello World! This is a test'
}
},
ready () {
console.log(d3.version)
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1 {
color: #42b983;
}
</style>
Your error isn't emitted from webpack, but from eslint.
I think the webpack part works as it should, in fact!
no-undef complains that you are using the global d3 without importing or defining it somewhere.
The good news is, that's easy to fix. Use any of the following three possibilities:
Just add the following block to your .eslintrc.js:
"globals": {
"d3": true
}
...or use eslint comments within the file that requires d3 implicitly (but that doesn't make much sense as you made it available globally and you would need to do this in every file you wish to use the global var):
/* eslint-disable no-undef */
...or you could relax the eslint rule in your .eslintrc.js config:
'rules': {
// all other rules...
'no-undef': 0
}
Additional links:
Direct link to the template's eslintrc file
The eslint 'standard' file the template extends
Further reading on eslint's no-undef rule

Resources