I am getting this error:
ERROR in ./~/react/react.js
Module not found: Error: Can't resolve './lib/React' in '/var/www/homelyfe/hl-app/node_modules/react'
# ./~/react/react.js 3:17-39
# ./app/index.js
ERROR in ./~/react-dom/index.js
Module not found: Error: Can't resolve './lib/ReactDOM' in '/var/www/homelyfe/hl-app/node_modules/react-dom'
# ./~/react-dom/index.js 3:17-42
# ./app/index.js
In my index.js (which webpack2 seems to be picking up correctly), when I do
import React from "react";
import { render } from "react-dom";
I get the above error. It seems, webpack is unable to find react. I have react & react-dom dependencies installed in package.json.
My webpack.config.js is:
const path = require("path");
const merge = require("webpack-merge");
const parts = require( "./webpack.config.parts" );
const PATHS = {
app : path.join( __dirname, "app" ),
build : path.join( __dirname, "build" )
};
const common = {
entry : {
app : "./app/index.js"
},
output : {
filename : "run.build.js",
path : PATHS.build
},
resolve : {
alias : {
assets : path.resolve( __dirname, "app/assets" ),
components : path.resolve( __dirname, "app/components" )
},
extensions : [ "js", "jsx" ]
}
};
var config;
switch( process.env.npm_lifecycle_event ){
case( "build-Prod" ): {
...
}
case( "start-Dev" ):
default: {
const eslintPath = path.join( __dirname, "/.eslintrc" );
config = merge( common,
parts.eslint( PATHS.app, eslintPath ),
parts.babel( PATHS.app ),
parts.devServer( PATHS.app ),
parts.htmlWebpackPlugin());
}
}
module.exports = config;
The webpack.config.parts file is:
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
exports.babel = function( path ){
var standardPresets = [
"react",
"es2015"
];
var presets;
presets = standardPresets;
}
return({
module: {
rules : [
{
test : /\.jsx?$/,
include : path,
use : [
{
loader: "babel-loader",
options : {
presets
}
}
]
}
]
}
});
};
exports.devServer = function() {
return ({
devServer: {
historyApiFallback: true,
hot: true,
inline: true,
stats: "errors-only"
},
plugins: [
new webpack.HotModuleReplacementPlugin({
multiStep: true
})
]
});
};
exports.eslint = function( path, configFilePath ){
return ({
module: {
rules : [
{
test : /\.jsx?$/,
enforce : "pre",
include : path,
use : [
{
loader : "eslint-loader",
options : {
configFile : configFilePath
}
}
]
}
]
}
});
};
exports.htmlWebpackPlugin = function( ) {
return ({
plugins: [
new HtmlWebpackPlugin({
title: "title"
})
]
});
};
I was having the same error a few moments ago. After espending a lot of time, I found the solution.
In your resolve.extensions note that the extensions includes the leading dots. In that way you have to replace it with the following:
extensions : [ ".js", ".jsx" ]
Changing that, your problem should be fixed.
Related
I have imports in project like this one:
import { ytheme } from "./ytheme.js";
Why? Because:
https://www.typescriptlang.org/docs/handbook/2/modules.html#es-module-syntax
and Appending .js extension on relative import statements during Typescript compilation (ES6 modules) (the first answer)
Webpack tries to resolve it with an error:
Field 'browser' doesn't contain a valid alias configuration
<...>\src\client\components\ytheme.js.ts doesn't exist
Which obviously won't work. The correct path should be:
<...>\src\client\components\ytheme.ts
The question: How do I configure webpack to remove '.js' before appending '.ts' when resolving imports?
=========== Details ==========
webpack.config.js:
const path = require("path");
const fs = require("fs");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin").CleanWebpackPlugin;
const ReactRefreshWebpackPlugin = require("#pmmmwh/react-refresh-webpack-plugin");
const isDevelopment = process.env.NODE_ENV !== "production";
const pathes = (() => {
const proj = path.resolve(__dirname);
const projParts = proj.split(path.sep);
const projName = projParts[projParts.length - 1];
const root = path.resolve(__dirname, "");
return {
root,
proj,
projName,
resources: path.resolve(proj, "resources"),
bundles: path.resolve(proj, "lib/bundles", projName),
};
})();
for (let k in pathes) console.log(`pathes.${k} = ${pathes[k]}`);
const NODE_ENV = "development";
let BUILD_DATE = new Date();
BUILD_DATE.setTime(BUILD_DATE.getTime() + 3 * 60 * 60 * 1000);
BUILD_DATE = JSON.stringify(BUILD_DATE);
BUILD_DATE = BUILD_DATE.substr(1, 10) + " " + BUILD_DATE.substr(12, 8);
console.log("");
console.log("BUILD_DATE = " + BUILD_DATE);
console.log("");
let package_json;
let manifest_json;
package_json = JSON.parse(fs.readFileSync(path.resolve(pathes.root, "package.json"), { encoding: "utf-8" }));
manifest_json = JSON.parse(fs.readFileSync(path.resolve(pathes.resources, "manifest.json"), { encoding: "utf-8" }));
let tsconf = eval("(()=>(" + fs.readFileSync("tsconfig.json", "utf-8") + "))()");
let moduleAliases = {};
for (let k in tsconf.compilerOptions.paths) {
let v = tsconf.compilerOptions.paths[k];
moduleAliases[k] = path.resolve(pathes.root, "ts_out", v[0]);
}
let excludedModules = [
"fs",
"sql-prettier",
"prettier",
"express",
"socket.io",
"better-sqlite3",
"sqlite3",
"child_process",
];
module.exports = {
// TODO REMOVED ON 2020-13-11
// node: {
// fs: "empty",
// child_process: "empty",
// },
mode: "development",
entry: [path.resolve(pathes.proj, "src/client/indexSmall.tsx")],
devtool: "inline-source-map",
devServer: {
contentBase: "./resources",
hot: true,
},
resolve: {
fallback: {
crypto: false,
fs: false,
child_process: false,
path: false,
constants: false,
util: false,
assert: false,
stream: false,
// crypto: require.resolve("crypto-browserify"),
// fs:null,
},
// root: path.join(pathes.proj, 'js'),
// modulesDirectories: ['node_modules'],
extensions: ["", ".ts", ".tsx", ".js", ".jsx", ".json"],
alias: {
"react-dom": "#hot-loader/react-dom",
...moduleAliases,
},
},
output: {
path: pathes.bundles,
filename: "bundle.js",
},
module: {
rules: [
{
test: (modulePath0) => {
let modulePath = modulePath0.split(path.sep);
for (let excludedModule of excludedModules) if (modulePath.includes(excludedModule)) return true;
return false;
},
use: "null-loader",
},
{
test: /\.css$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
],
},
{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"sass-loader", // compiles Sass to CSS, using Node Sass by default
],
},
{
test: /\.(j|t)sx?$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
cacheDirectory: true,
babelrc: false,
presets: ["#babel/preset-typescript", "#babel/preset-react"],
plugins: [
["#babel/plugin-proposal-decorators", { legacy: true }],
"#babel/proposal-optional-chaining",
["#babel/proposal-class-properties", { legacy: true }],
"#babel/proposal-object-rest-spread",
// "react-hot-loader/babel",
[
"module-resolver",
{
root: ["./"],
alias: moduleAliases,
},
],
// "#babel/transform-modules-commonjs",
],
},
},
},
],
},
plugins: [
new webpack.DefinePlugin({
BROWSER: "true",
"process.env.BROWSER": "true",
NODE_ENV: JSON.stringify(NODE_ENV),
BUILD_DATE: JSON.stringify(BUILD_DATE),
// BASE_URL:JSON.stringify(private_js ? private_js.url : 'http://localhost')
}),
new CleanWebpackPlugin(),
// new webpack.NamedModulesPlugin(), // TODO REMOVED ON 2020-13-11
new HtmlWebpackPlugin({ title: manifest_json.name }),
isDevelopment && new webpack.HotModuleReplacementPlugin(),
isDevelopment && new ReactRefreshWebpackPlugin(),
],
// watchOptions : {
// aggregateTimeout : 300
// },
// "cheap-inline-module-source-map"
};
// console.log('YYAWEBPACK', JSON.stringify(module.exports.resolve.alias,null, "\t"));
The command I run dev server with:
webpack-cli serve --mode development --config webpack.frontend.config.js
Full error:
ERROR in ./src/client/indexSmall.tsx 7:0-48
Module not found: Error: Can't resolve './components/ytheme.js' in 'D:\b\Mine\GIT_Work\yatasks_one_api\src\client'
resolve './components/ytheme.js' in 'D:\b\Mine\GIT_Work\yatasks_one_api\src\client'
using description file: D:\b\Mine\GIT_Work\yatasks_one_api\package.json (relative path: ./src/client)
Field 'browser' doesn't contain a valid alias configuration
using description file: D:\b\Mine\GIT_Work\yatasks_one_api\package.json (relative path: ./src/client/components/ytheme.js)
Field 'browser' doesn't contain a valid alias configuration
D:\b\Mine\GIT_Work\yatasks_one_api\src\client\components\ytheme.js doesn't exist
.ts
Field 'browser' doesn't contain a valid alias configuration
D:\b\Mine\GIT_Work\yatasks_one_api\src\client\components\ytheme.js.ts doesn't exist
.tsx
Field 'browser' doesn't contain a valid alias configuration
D:\b\Mine\GIT_Work\yatasks_one_api\src\client\components\ytheme.js.tsx doesn't exist
.js
Field 'browser' doesn't contain a valid alias configuration
D:\b\Mine\GIT_Work\yatasks_one_api\src\client\components\ytheme.js.js doesn't exist
.jsx
Field 'browser' doesn't contain a valid alias configuration
D:\b\Mine\GIT_Work\yatasks_one_api\src\client\components\ytheme.js.jsx doesn't exist
.json
Field 'browser' doesn't contain a valid alias configuration
D:\b\Mine\GIT_Work\yatasks_one_api\src\client\components\ytheme.js.json doesn't exist
as directory
D:\b\Mine\GIT_Work\yatasks_one_api\src\client\components\ytheme.js doesn't exist
webpack 5.41.1 compiled with 2 errors in 2120 ms
i 「wdm」: Failed to compile.
As a workaround the following snippet seems to work:
{ // webpack.config.cjs
plugins: [
new webpack.NormalModuleReplacementPlugin(/.*/, function (resource) {
const lowerCaseRequest = resource.request.toLowerCase();
if (
!lowerCaseRequest.includes("node_modules") &&
lowerCaseRequest.endsWith(".js") &&
lowerCaseRequest[0] === "." &&
resource.context.startsWith(path.resolve(__dirname))&&
!resource.context.toLowerCase().includes("node_modules")
) {
resource.request = resource.request.substr(0, resource.request.length - 3) + ".ts";
resource.request });
}
}),
...]
}
I'm trying to implement a solution for reading configurations from some file in my react app... don't know what is the best practice but I adapted the following way and tried implementing it:
1) under the root of my app (in parallel to webpack.config.js)
I created a file called: config.dev.json with this content:
{
"protocol" : "http",
"host" : "localhost",
"port" : "8080"
}
2) to webpack.config.js added my code (TODO part at the end):
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const rtlcss = require('rtlcss');
const webpack = require("webpack");
const useExternalCss =
process.env.CARBON_REACT_STORYBOOK_USE_EXTERNAL_CSS === 'true';
const useStyleSourceMap =
process.env.CARBON_REACT_STORYBOOK_USE_STYLE_SOURCEMAP === 'true';
const useRtl = process.env.CARBON_REACT_STORYBOOK_USE_RTL === 'true';
const styleLoaders = [
{
loader: 'css-loader',
options: {
importLoaders: 2,
sourceMap: useStyleSourceMap,
},
},
{
loader: 'postcss-loader',
options: {
plugins: () => {
const autoPrefixer = require('autoprefixer')({
browsers: ['last 1 version', 'ie >= 11'],
});
return !useRtl ? [autoPrefixer] : [autoPrefixer, rtlcss];
},
sourceMap: useStyleSourceMap,
},
},
{
loader: 'sass-loader',
options: {
includePaths: [path.resolve(__dirname, '..', 'node_modules')],
data: `
$feature-flags: (
ui-shell: true,
);
`,
sourceMap: useStyleSourceMap,
},
},
];
module.exports = (baseConfig, env, defaultConfig) => {
defaultConfig.devtool = useStyleSourceMap ? 'source-map' : '';
defaultConfig.optimization = {
...defaultConfig.optimization,
minimizer: [
new TerserPlugin({
sourceMap: true,
terserOptions: {
mangle: false,
},
}),
],
};
defaultConfig.module.rules.push({
test: /-story\.jsx?$/,
loaders: [
{
loader: require.resolve('#storybook/addon-storysource/loader'),
options: {
prettierConfig: {
parser: 'babylon',
printWidth: 80,
tabWidth: 2,
bracketSpacing: true,
trailingComma: 'es5',
singleQuote: true,
},
},
},
],
enforce: 'pre',
});
defaultConfig.module.rules.push({
test: /\.scss$/,
sideEffects: true,
use: [
{ loader: useExternalCss ? MiniCssExtractPlugin.loader : 'style-loader' },
...styleLoaders,
],
});
if (useExternalCss) {
defaultConfig.plugins.push(
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css',
})
);
}
//TODO
if (!defaultConfig.resolve) {
defaultConfig.resolve = {};
}
if (!defaultConfig.resolve.alias) {
defaultConfig.resolve.alias = {};
}
defaultConfig.resolve.alias.Config = process.env.NODE_ENV === 'production'
? path.resolve('./config.prod.json')
: path.resolve('./config.dev.json');
return defaultConfig;
};
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development'),
'BASE_URL': JSON.stringify('http://localhost:3000/')
}
})
],
// externals: {
// 'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? require('./config.prod.json') : require('./config.dev.json'))
// }
//
// // externals: {
// // 'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? {
// // serverUrl: "http://test.com:8080"
// // } : {
// // serverUrl: "http://localhost:8080"
// // })
// // }
//
}
3) and tried to use it from some component that way:
let Config = require('Config')
but I'm getting:
./src/stores/RestService.js
Module not found: Can't resolve 'Config' in 'C:
If you want to setup configuration without webpack (e.g. when using create-react-app) this is how I'd suggest:
Create config folder (or name it however you want) and add your config files and index file:
config.dev.json
config.prod.json
index.js
And then inside your config/index.js file:
if (process.env.NODE_ENV === 'development') {
module.exports = require('./config.dev.json')
} else {
module.exports = require('./config.prod.json')
}
Use it with import config from './config';
why not use like this
at your package.json
"scripts": {
"develop": "PORT=8080 HOST=localhost PROTOCOL=http node ."
"production": "Your config here"
}
create a config/app.js
const config = process.env
module.export = {
port: config.PORT,
protocol: config.PROTOCOL,
host: config.HOST,
}
In your webpack ( actually, i don't know why you have to import config in your webpack and reexport it. if you want your jsx or js files able to read the PORT, HOST, and LOCALHOST, u can just follow until step 2, and u can freely get your config files in any your app.js files )
const config = require('./path/to/config/app.js')
module.exports = {
externals: {
config: config,
}
}
First you need the configuration file in your bundle, it's not an external (so we only need to remove the external part).
Then you need the config file to be resolved as a diffrent file depending on the environment (prod or dev, using resolve.alias).
Be carefull of the working directory too, either run webpack from the project's folder, or use the context configuration option.
Suggested webpack config (relevant part in the end):
module.exports = (baseConfig, env, defaultConfig) => {
defaultConfig.devtool = useStyleSourceMap ? 'source-map' : '';
defaultConfig.optimization = {
...defaultConfig.optimization,
minimizer: [
new TerserPlugin({
sourceMap: true,
terserOptions: {
mangle: false,
},
}),
],
};
defaultConfig.module.rules.push({
test: /-story\.jsx?$/,
loaders: [
{
loader: require.resolve('#storybook/addon-storysource/loader'),
options: {
prettierConfig: {
parser: 'babylon',
printWidth: 80,
tabWidth: 2,
bracketSpacing: true,
trailingComma: 'es5',
singleQuote: true,
},
},
},
],
enforce: 'pre',
});
defaultConfig.module.rules.push({
test: /\.scss$/,
sideEffects: true,
use: [
{ loader: useExternalCss ? MiniCssExtractPlugin.loader : 'style-loader' },
...styleLoaders,
],
});
defaultConfig.module.rules.push({
test: /\.json$/,
use: [
{ loader: useExternalCss ? MiniCssExtractPlugin.loader : 'style-loader' },
...styleLoaders,
],
});
if (useExternalCss) {
defaultConfig.plugins.push(
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css',
})
);
}
// ensure resolve alias present in the config
if (!defaultConfig.resolve) {
defaultConfig.resolve = {};
}
if (!defaultConfig.resolve.alias) {
defaultConfig.resolve.alias = {};
}
// resolve the alias to the right config file according to NODE_ENV
// you'll have to correctly set <relative path to your config>
defaultConfig.resolve.alias.Config = process.env.NODE_ENV === 'production'
? path.resolve(__dirname, '<relative path to your config>/config.prod.json')
: path.resolve(__dirname, '<relative path to your config>/config.dev.json');
return defaultConfig;
};
don't forget to remove this:
module.exports = {
externals: {
'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? require('./config.prod.json') : require('./config.dev.json'))
}
// externals: {
// 'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? {
// serverUrl: "http://test.test.com:8080"
// } : {
// serverUrl: "http://localhost:8080"
// })
// }
}
As it will prevent webpack from bundling the file.
You can use DefinePlugin to define setting config in webpack like this
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development'),
'BASE_URL': JSON.stringify('http://localhost:5000/')
}
})
],
Then simply use
process.env.BASE_URL
or
process.env.NODE_ENV
I'm referencing an image inside my .JSX file but the generated URL is wrong.
It looks like this : http://localhost:43124/dist/dist/9ee7eb54c0eb428bb30b599ef121fe25.jpg
The folder "dist" exists with the picture but not "dist/dist". I think the problem comes from my Webpack.config.js. Here are the files :
module.d.ts
I instruct Typescript what to do with image files as mentionned here.
declare module '*.jpg'
declare module '*.svg'
Layout.tsx
I reference my logo inside React so it can be packed by Webpack.
/// <reference path="./module.d.ts"/>
import * as React from 'react';
import logo from '../img/logo.svg';
export class Layout extends React.Component<{}, {}> {
public render() {
return <img src="{logo}" width="220" alt="logo" />
}
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const merge = require('webpack-merge');
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
// Configuration in common to both client-side and server-side bundles
const sharedConfig = () => ({
stats: { modules: false },
resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] },
output: {
filename: '[name].js',
publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
rules: [
{ test: /\.tsx?$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [new CheckerPlugin()]
});
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig(), {
entry: { 'main-client': './ClientApp/boot-client.tsx' },
module: {
rules: [
{ test: /\.css$/, use: ExtractTextPlugin.extract({ use: isDevBuild ? 'css-loader' : 'css-loader?minimize' }) }
]
},
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new ExtractTextPlugin('style.css'),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin()
])
});
return [clientBundleConfig];
};
I used the default Visual Studio ASP.NET Core React + Redux template.
I know this is a common question for webpack; it's really hard to debug something if it won't give you any information about the cause or location of the error.
I'm getting the error:
Error: 'output.filename' is required, either in config file or as --output-filename
I know it has to do with a syntax error somewhere, but I'm too new to webpack to figure it out.
Here's my config file. It's called "webpack.config.js" in the root folder (i.e. the folder in which I initially ran: npm init).
const webpack = require('webpack');
const path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const RewriteImportPlugin = require("less-plugin-rewrite-import");
const root_dir = path.resolve(__dirname)
const src_dir = path.resolve(__dirname, "webpack_src")
const build_dir = path.resolve(__dirname, "webpack_bin")
const node_mod_dir = path.resolve(__dirname, 'node_modules');
const extractLESS = new ExtractTextPlugin('style.css');
const config = {
entry: {
index: path.resolve(src_dir, 'index.js')
},
output: {
path: build_dir,
filename: 'bundle.js'
},
resolve: {
modules: [root_dir, 'node_modules'],
},
module: {
rules: [
{
loader: 'babel-loader',
test: /\.(js)$/
},
{
use: extractLESS.extract({
fallback: 'style-loader',
use: [
'css-loader',
{
loader: 'less-loader',
options: {
paths: [root_dir, node_mod_dir],
plugins: [
new RewriteImportPlugin({
paths: {
'../../theme.config': __dirname + '/semantic_ui/theme.config',
}
})
]
}
}]
}),
test: /\.less$/
},
{
use: ['file-loader'],
test: /\.(png|jpg|gif|woff|svg|eot|ttf|woff2)$/
},
]
},
plugins: [
extractLESS,
new webpack.optimize.ModuleConcatenationPlugin()
]
};
module.exports = {
config
};
You're exporting module.exports = { config }, which means that you are exporting an object with one property, namely config, but webpack expects the object to be your entire config. Webpack requires output.filename, whereas you only provide config.output.filename.
The export should be your config:
module.exports = config;
I'm using extract-text-webpack-plugin 2.0.0-rc.3 with Webpack 2.2.1 and am getting this error when running the build:
/node_modules/extract-text-webpack-plugin/index.js:259
var shouldExtract = !!(options.allChunks || chunk.isInitial());
^
TypeError: chunk.isInitial is not a function
Here is my webpack.config.js:
'use strict';
const argv = require('yargs').argv;
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const webpack = require('webpack');
module.exports = (function () {
let config = {
entry : './' + process.env.npm_package_config_paths_source + '/main.js',
output : {
filename : 'main.js'
},
watch : !!argv.watch,
vue : {
loaders : {
js : 'babel-loader',
// Create separate CSS file to prevent unstyled content
sass : ExtractTextPlugin.extract("css!sass?sourceMap") // requires `devtool: "#source-map"`
}
},
module : {
rules : [
{
test : /\.js$/,
use : 'babel-loader',
exclude : '/node_modules/'
},
{
test : /\.vue$/,
use : 'vue-loader',
options : {
loaders : {
'scss' : 'vue-style-loader!css-loader!sass-loader',
'sass' : 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
},
}
}
]
},
plugins : [
new webpack.DefinePlugin({
'process.env' : {
npm_package_config_paths_source : '"' + process.env.npm_package_config_paths_source + '"'
}
}),
new ExtractTextPlugin("style.css")
],
resolve : {
alias : {
'vue$' : 'vue/dist/vue.common.js'
}
},
babel : {
"presets" : ["es2015", "stage-2"],
"comments" : false,
"env" : {
"test" : {
"plugins" : ["istanbul"]
}
}
},
devtool : "#source-map" // #eval-source-map is faster but not compatible with ExtractTextPlugin
};
if (process.env.NODE_ENV === 'production') {
config.plugins = [
// short-circuits all Vue.js warning code
new webpack.DefinePlugin({
'process.env' : {
NODE_ENV : '"production"',
npm_package_config_paths_source : '"' + process.env.npm_package_config_paths_source + '"'
}
}),
// minify with dead-code elimination
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin("style.css")
];
config.devtool = "#source-map";
}
return config;
})();
When I remove new ExtractTextPlugin("style.css") from the plugins array the build runs fine, but doesn't create style.css.
If I add the allChunks: true option the error becomes this:
/node_modules/webpack/lib/Chunk.js:80
return this.entrypoints.length > 0;
^
TypeError: Cannot read property 'length' of undefined
In case you are writing style rules in .vue file or seprate .scss file, with below webpack configurations you can achieve what you're searching for:
webpack.confi.js:
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
....
....
module.exports = {
....
....
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
'scss': ExtractTextPlugin.extract('css-loader!sass-loader'),
'sass': ExtractTextPlugin.extract('css-loader!sass-loader?indentedSyntax')
}
}
},
....
....
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('css-loader!sass-loader')
}
....
....
] // rules end
}, // module end
plugins: [
new ExtractTextPlugin('style.css')
],
....
}
Just make sure that you have installed these modules/loaders via NPM:
css-loader
sass-loader
node-sass
extract-text-webpack-plugin