Module not found: Error: Cannot resolve module 'module' - javascript

I want to load module from variable string
var abc = './../containers/BlankContainer';
require(abc);
but it cannot find module, so I install 'require-from-string' module from npm.
Now when I build it's giving error
ERROR in ./~/require-from-string/index.js
Module not found: Error: Cannot resolve module 'module' in D:\Nilay\RnD\node_modules\require-from-string
# ./~/require-from-string/index.js 3:13-30
I found it is webpack issue, here is my webpack config:
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin')
var entry = [path.resolve(__dirname, 'app/bootstrap.js')];
var output = {
path: path.resolve(__dirname, 'public/dist'),
filename: 'bundle-[name].js',
publicPath: "dist/"
};
var modules = {
loaders: [
{ test: /\.json$/, loader: "json-loader" },
{ test: /\.js$/,
loader: ['babel-loader'], exclude: /node_modules/, query: { cacheDirectory: 'babel_cache', presets: ['react', 'es2015'] } },
{ test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!autoprefixer-loader") },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader" },
{ test: /\.(woff|woff2)$/, loader: "file-loader" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader" }
]
};
var plugins = [
new ExtractTextPlugin("bundle.css"),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery'
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ // minimize/compress all js chunks
compress: { warnings: false },
mangle: false,
sourcemap: false,
beautify: false,
dead_code: true
})
]
module.exports = {
entry: entry,
output: output,
stats: { colors: true },
watch: true,
module: modules,
plugins: plugins,
resolveLoader: {
root: path.join(__dirname, 'node_modules')
},
resolve: {
modules: [path.resolve(__dirname, '/app/routes'), 'node_modules/'],
descriptionFiles: ['package.json'],
extensions: ['', '.js', '.ts']
}
};
How can I resolve it?

Related

vuejs npm dev server does not show updated output

I am using vuejs in wordpress theme, everything is properly setup and working.
npm run build works perfectly and creates dist and wordpress picks up all content from it.
What's the issue then?
npm run dev also works in the console but when I made any change in a vue template it compiles but IT DOES NOT SHOW UPDATED OUTPUT.
Please guide and help.
webpack.config.dev.js
const path = require('path');
const webpack = require('webpack');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const fs = require('fs');
const autoprefixer = require('autoprefixer');
if (fs.existsSync(path.resolve(__dirname, '../.env.example')) === true) {
fs.renameSync(
path.resolve(__dirname, '../.env.example'),
path.resolve(__dirname, '../.env'),
);
}
module.exports = (options = {}) => {
const config = {
entry: {
admin: './src/admin.js',
public: './src/public.js',
},
output: {
path: path.resolve(__dirname, '../dist'),
publicPath: 'http://localhost:9000/',
filename: 'js/[name].js',
},
module: {
rules: [{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
sass: 'vue-style-loader?sourceMap!css-loader?sourceMap!sass-loader?indentedSyntax&sourceMap',
scss: 'vue-style-loader?sourceMap!css-loader?sourceMap!sass-loader?sourceMap',
},
preserveWhitespace: false,
postcss: [autoprefixer()],
},
},
{
test: /\.js$/,
loader: 'babel-loader',
options: {
cacheDirectory: true,
},
exclude: /node_modules/,
},
{
test: /\.js|\.vue$/,
use: [{
loader: 'eslint-loader',
options: {
configFile: path.resolve(__dirname, '../.eslintrc.json'),
},
}, ],
enforce: 'pre',
exclude: /node_modules/,
},
{
test: /\.(s)?css$/,
use: [
'vue-style-loader?sourceMap',
'css-loader?sourceMap',
'postcss-loader?sourceMap',
'sass-loader?sourceMap',
],
},
{
test: /\.png|\.jpg|\.gif|\.svg|\.eot|\.ttf|\.woff|\.woff2$/,
loader: 'file-loader',
query: {
name: '[hash].[ext]',
outputPath: 'static/',
},
exclude: /node_modules/,
},
{
test: /\.json$/,
loader: 'json-loader',
},
],
},
plugins: [
new webpack.LoaderOptionsPlugin({
options: {
postcss: [autoprefixer()],
context: '/',
},
}),
new StyleLintPlugin({
configFile: path.resolve(__dirname, '../.stylelintrc.json'),
syntax: 'scss',
files: ['**/*.s?(a|c)ss', '**/*.vue'],
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new webpack.optimize.ModuleConcatenationPlugin(),
],
devServer: {
compress: true,
contentBase: path.join(__dirname, '../dist'),
headers: {
'Access-Control-Allow-Origin': 'http://localhost',
},
hot: true,
public: 'localhost:9000',
port: 9000,
overlay: {
errors: true,
warnings: true,
},
},
devtool: 'eval-source-map',
externals: {
jquery: 'jQuery',
},
resolve: {
alias: {
PublicJSUtilities: path.resolve(
__dirname,
'../src/public/js/utilities',
),
PublicCSSAbstracts: path.resolve(
__dirname,
'../src/public/css/abstracts',
),
PublicImg: path.resolve(__dirname, '../src/public/img'),
masonry: 'masonry-layout',
isotope: 'isotope-layout',
},
},
watch: options.watch === 'true',
};
return config;
};
webpack.vue.build.js
const path = require('path');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const fs = require('fs');
const autoprefixer = require('autoprefixer');
if (fs.existsSync(path.resolve(__dirname, '../.env')) === true) {
fs.renameSync(
path.resolve(__dirname, '../.env'),
path.resolve(__dirname, '../.env.example'),
);
}
module.exports = () => {
const config = {
entry: {
admin: './src/admin.js',
public: './src/public.js',
},
output: {
path: path.resolve(__dirname, '../dist'),
publicPath: '',
filename: 'js/[name].js',
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
sass: ExtractTextPlugin.extract({
fallback: 'vue-style-loader?sourceMap',
use: 'css-loader?sourceMap!sass-loader?sourceMap',
}),
scss: ExtractTextPlugin.extract({
fallback: 'vue-style-loader?sourceMap',
use: 'css-loader?sourceMap!sass-loader?sourceMap',
}),
},
preserveWhitespace: false,
postcss: [autoprefixer()],
},
},
{
test: /\.js$/,
loader: 'babel-loader',
options: {
cacheDirectory: true,
},
},
{
test: /\.js|\.vue$/,
use: [
{
loader: 'eslint-loader',
options: {
configFile: path.resolve(__dirname, '../.eslintrc.json'),
},
},
],
enforce: 'pre',
exclude: /node_modules/,
},
{
test: /\.(s)?css$/,
loader: ExtractTextPlugin.extract({
fallback: 'vue-style-loader?sourceMap',
use: 'css-loader!postcss-loader!sass-loader',
}),
},
{
test: /\.png|\.jpg|\.gif|\.svg|\.eot|\.ttf|\.woff|\.woff2$/,
loader: 'file-loader',
query: {
name: '[hash].[ext]',
outputPath: 'static/',
publicPath: '../',
},
exclude: /node_modules/,
},
],
},
plugins: [
new CleanWebpackPlugin(['dist'], {
root: path.resolve(__dirname, '../'),
verbose: true,
}),
new webpack.LoaderOptionsPlugin({
options: {
postcss: [autoprefixer()],
context: '/',
},
}),
new ExtractTextPlugin('css/[name].css'),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"',
},
}),
new StyleLintPlugin({
configFile: path.resolve(__dirname, '../.stylelintrc.json'),
syntax: 'scss',
files: ['**/*.s?(a|c)ss', '**/*.vue'],
}),
new webpack.optimize.ModuleConcatenationPlugin(),
],
externals: {
jquery: 'jQuery',
},
resolve: {
alias: {
PublicJSUtilities: path.resolve(
__dirname,
'../src/public/js/utilities',
),
PublicCSSAbstracts: path.resolve(
__dirname,
'../src/public/css/abstracts',
),
PublicImg: path.resolve(__dirname, '../src/public/img'),
masonry: 'masonry-layout',
isotope: 'isotope-layout',
},
},
};
return config;
};
Screenshot to get some idea about folder structure:
http://prntscr.com/n0cbg1
add --watch in start field in package.json file.
or use this command for executing:
npm run build -- --watch

Can't load templates with routeprovider when using webpack

I recentley migrated from grunt to webpack and I can't figure how to require/import my templates. I have looked at several similar issues with no luck.
Here is my webpack.config file:
var webpack = require('webpack');
var globby = require('globby');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var AssetsPlugin = require('assets-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
app: globby.sync(['./app/app.js','./app/app.run.js', './app/app.config.js', './app/**/*.js']),
styles: globby.sync(['./content/styles/*.css']),
images: globby.sync(['./content/images/*.*']),
vendor: [
// removed to save space
]
},
output: {
filename: './scripts/[name].bundle.js',
path: path.join(__dirname, "public")
},
devServer: {
port: 1384,
contentBase: './public/'
},
// Enable sourcemaps for debugging webpack's output.
devtool: 'source-map',
module: {
rules: [
{ test: /\.less$/,
loader: "less-loader",
include: path.resolve(__dirname, "content", "styles", "less")
},
{
test: /\.html$/,
use: [
{
loader: 'ngtemplate-loader',
options: {
angular: true,
},
},
{
loader: 'raw-loader',
},
{
loader: 'html-loader'
},
{
loader: "ngtemplate!html?module=myTemplates&relativeTo=" +
(path.resolve(__dirname, './app/**'))
},
],
/*
exclude: [/node_modules/]
*/
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' }),
},
{
test: /\.(ico)$/,
loader: "url-loader?name=./[name].[ext]",
include: path.resolve(__dirname, "content", "images")
},
{
test: /\.(jpg|jpeg|gif|png|tiff|svg)$/,
loader: "file-loader?name=./images/[name].[ext]",
include: path.resolve(__dirname, "content", "images")
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?minetype=application/font-woff&name=./fonts/[name].[ext]'
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader?name=./fonts/[name].[ext]'
},
{
test: require.resolve('adal-angular/lib/adal'),
loader: 'expose-loader?AuthenticationContext'
},
{
test: /\.js$/,
enforce: "pre",
loader: 'source-map-loader'
}
],
},
plugins: [
new webpack.DefinePlugin({
ADMIN_API_URL: JSON.stringify('http://localhost:41118/api/'),
API_URL: JSON.stringify('http://localhost:32605/api/'),
GLOBAL_ADMIN_URL: JSON.stringify('https://adminapi.tradesolution.no/')
}),
new HtmlWebpackPlugin({
template: './app/layout.ejs',
filename: 'index.html'
}),
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: './scripts/vendor.bundle.js' }),
new ExtractTextPlugin({ filename: './styles/[name].bundle.css' }),
/*new CleanWebpackPlugin(['public'], {
verbose: false
}),
*/
new AssetsPlugin({
filename: 'webpack.assets.json',
path: './public/scripts',
prettyPrint: true
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery',
"window.AuthenticationContext": "AuthenticationContext",
_: 'underscore'
}),
],
externals: [
{ xmlhttprequest: '{XMLHttpRequest:XMLHttpRequest}' }
],
}
The public folder builds as it should with .js, styles, images etc. But simple navigation results in this error:
ERROR in ./app/app.config.js
Module not found: Error: Can't resolve 'app/varegruppe/templates/index.html' in 'C:\Users\oystein\work\EPD.SPA\EpdSPA\app'
# ./app/app.config.js 50:25-71
Here is an example of how the routes are defined:
$routeProvider.when('/produkteier', {
templateUrl: require('app/produkteier/templates/view.html')
})
Using this plugin I managed to copy all the html files in to the public directory, with the following config:
var CopyWebpackPlugin = require('copy-webpack-plugin');
new CopyWebpackPlugin([
{from: './app/**/*.html', to: './'}
])

Extract text Webpack plugin compile error

I'm using "webpack": "^3.1.0" and "extract-text-webpack-plugin": "^1.0.1"
Trying to compile sass and I get the following error: Error: "extract-text-webpack-plugin" loader is used without the corresponding plugin, refer to https://github.com/webpack/extract-text-webpack-plugin for the usage example
I have used this as per the documents provided - don't understand why I'm getting webpack build errors.
Here is my webpack file:
const debug = process.env.NODE_ENV !== "production";
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
context: path.join(__dirname, "src"),
devtool: debug ? "inline-sourcemap" : null,
entry: ['./js/client.js', './styles/base.scss'],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'],
}
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
//resolve-url-loader may be chained before sass-loader if necessary
use: ['css-loader', 'sass-loader']
})
}
]
},
output: {
path: __dirname + "/src/",
filename: "client.min.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
new ExtractTextPlugin('main.css')
],
};
You need to include something to tell where webpack to look, for example:
{
test: /(\.css|\.scss|\.sass)$/,
include: path.join(__dirname, "../src"), // Include or exclude node modules
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ["css-loader", "sass-loader"],
}),
},
Here is my webpack.config.babel.js file I hope this will helps you.
import HtmlWebpackPlugin from 'html-webpack-plugin';
import ExtractTextPlugin,{extract} from 'extract-text-webpack-plugin';
import {resolve,join} from 'path';
// import webpack from 'webpack';
// var isProd = process.env.NODE_ENV === 'production'; //return true or false
// var cssDev = [ "style-loader", "css-loader", "sass-loader" ];
// var cssProd = extract({
// fallback: "style-loader",
// use: [ "css-loader", "sass-loader"],
// publicPath:'/dist'
// });
// var cssConf = isProd ? cssProd : cssDev;
module.exports = {
entry: {
app:'./src/app.js',
},
output: {
path: join(__dirname, "dist"),
filename : '[name].bundle.js'
},
module: {
rules:[
{
test: /\.scss$/,
exclude: /node_modules/,
use: extract({
fallback: "style-loader",
use: [ "css-loader", "sass-loader"],
publicPath:'/dist'
})
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.(png|jpg|gif)$/,
use:"file-loader",
}
]
},
devServer:{
contentBase: join(__dirname, "dist"),
compress: true,
port: 9000,
stats:'errors-only',
},
plugins: [
new HtmlWebpackPlugin({
title: 'Webpack starter project',
template: './src/index.html',
hash:true,
excludeChunks: ['contact'],
minify:{
collapseWhitespace: true,
minifyCSS: true,
minifyJS:true,
}
}),
new ExtractTextPlugin({
filename: "app.css",
// disable: !isProd,
disable: false,
allChunks: true
}),
// new webpack.HotModuleReplacementPlugin(),
// new webpack.NamedModulesPlugin(),
]
}
you have to change the version of Extract Text Plugin
Instead of new ExtractTextPlugin('main.css') use new
ExtractTextPlugin({ filename: "main.css"})

Sourcemap Sass with Webpack (2)

I am using Webpack 2 for building my Angular (4) app. I have it working, but I am trying to figure out how to generate sourcemaps for my scss. In my components I load my scss with styleUrls Adding the options: { sourceMap: true } is not working. I do not want to extract the styles for components, because then the ViewEncapsulation is not working anymore. The .global.scss I use are needed everywhere, so I do extract these and this part works fine. Can someone tell me how to generate my sourcemaps (is it even possible with Angular)? Below is my webpack.config.js .
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const autoprefixer = require('autoprefixer');
const path = require('path');
module.exports = {
devtool: 'inline-source-map',
devServer: {
port: 3000,
contentBase: '/www',
inline: true
},
entry: {
polyfills: './src/polyfills.ts',
vendor: './src/vendor.ts',
app: './src/bootstrap.ts'
},
output: {
path: path.join(__dirname, '../www/'),
filename: '[name].bundle.js'
},
resolve: {
modules: [ path.join(__dirname, 'node_modules') ],
extensions: ['.js', '.ts', '.html']
},
module: {
loaders: [{
test: /\.ts$/,
exclude: /node_modules/,
use: ['awesome-typescript-loader', 'angular2-template-loader']
}, {
test: /\.html$/,
use: 'html-loader'
},{
test: /\.global\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use:[{
loader: 'css-loader',
options: {
sourceMap: true
}
}, {
loader: 'postcss-loader'
}, {
loader: 'sass-loader',
options: {
sourceMap: true,
}
}]
}),
}, {
test: /\.scss$/,
use: [ {
loader: "raw-loader"
}, {
loader: 'resolve-url-loader'
}, {
loader: 'postcss-loader'
}, {
loader: "sass-loader", options: {
sourceMap: true
}
}],
exclude: /node_modules/
}, {
test: /.(png|woff(2)?|eot|ttf|svg)(\?[a-z0-9=\.]+)?$/,
use: 'url-loader'
}]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
}),
new ExtractTextPlugin('global-styles.css'),
new webpack.optimize.CommonsChunkPlugin({
name: 'polyfills',
chunks: ['polyfills']
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
chunks: ['vendor']
}),
new webpack.optimize.CommonsChunkPlugin({
name: ['polyfills', 'vendor'].reverse()
})
]
};

In production Webpack 2.2.0.rc-0 will uglify/minify vendor.js and manifest.js but not bundle.js

I'm trying to figure out why my vendor and manifest files are minified and uglified but my bundle is not. Could it be the order of the plugins? Maybe something to do with the CommonsChunkPlugin?
This is my UglifyJsPlugin code:
new webpack.optimize.UglifyJsPlugin({
debug: false,
minimize: true,
sourceMap: false,
output: {
comments: false
},
compressor: { // eslint-disable-line camelcase
warnings: false,
unused: true,
dead_code: true
},
mangle: false
}),
and this is my webpack config object a whole:
const webpack = require('webpack');
const conf = require('./gulp.conf');
const path = require('path');
const del = require('del');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const pkg = require('../package.json');
const autoprefixer = require('autoprefixer');
module.exports = {
entry: {
bundle: `./${conf.path.src('index')}`,
vendor: `./src/app/dependencies`,
},
output: {
path: path.join(process.cwd(), conf.paths.dist),
filename: '[name].[chunkhash].js'
},
module: {
rules: [
{
test: /.json$/,
use: ['json-loader']
},
{
test: /.ts$/,
exclude: /node_modules/,
enforce: 'pre',
use: ['tslint-loader']
},
{
test: /\.(css|scss)$/,
use: [
'style-loader',
'css-loader',
'sass-loader',
'postcss-loader'
]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: [
'ng-annotate-loader',
'babel-loader'
]
},
{
test: /\.ts$/,
exclude: /node_modules/,
use: ['ts-loader']
},
{
test: /.html$/,
use: ['html-loader']
},
{
test: /\.(jade|pug)$/,
use: ['pug-html-loader']
},
{
test: /\.(eot|woff|woff2|ttf|svg|png|jpg)$/,
use: ['url-loader?limit=30000&name=[name]-[hash].[ext]']
},
{
test: /\.less$/,
use: ['style-loader','css-loader', 'less-loader']
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
debug: false,
minimize: true,
sourceMap: false,
output: {
comments: false
},
compressor: { // eslint-disable-line camelcase
warnings: false,
unused: true,
dead_code: true
},
mangle: false
}),
new webpack.optimize.CommonsChunkPlugin({
names: ['vendor', 'manifest']
}),
new webpack.optimize.OccurrenceOrderPlugin(),
// new webpack.NoErrorsPlugin(), // emits no scripts to browser if there are any errors at all
new HtmlWebpackPlugin({
template: conf.path.src('index.html'),
inject: true
}),
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
conf.paths.src
),
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"'
}),
new ExtractTextPlugin('index-[contenthash].css'),
new webpack.LoaderOptionsPlugin({
options: {
postcss: () => [autoprefixer],
resolve: {},
ts: {
configFileName: 'tsconfig.json'
},
tslint: {
configuration: require('../tslint.json')
}
}
}),
new CopyWebpackPlugin([{
from: path.join(conf.paths.src, 'integration', 'embedder', 'embedder.js'),
to: path.join('integration', 'embedder', 'embedder.js')
}])
],
resolve: {
extensions: [
'.webpack.js',
'.web.js',
'.js',
'.ts'
]
}
};
turns out the answer was to add an options config to the babel-loader to include presets es2015 as so:
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'ng-annotate-loader'
},
{
loader: 'babel-loader',
options: {
presets: ['es2015'],
}
}
]
},
This is needed for uglify/minifying es6 code with webpack 2.

Categories