I could not import exported variables from an es2015 NPM module - npm

I have an npm module named sidebar. I use webpack to compile the es2015 src files into a single file. So far running webpack does not output any problem and creates a file, lib/sidebar.min.js
I have set the it to be the main file in package.json
...
"description": "",
"main": "lib/sidebar.min.js",
"scripts": {
...
I have this in my src/index.js file
export const foo = 'foo'
export const bar = 'bar'
I tried using this module in my main project
import { foo, bar } from 'sidebar'
console.log(foo)
console.log(bar)
Both console log calls outputs undefined
After searching the internet for hours, I am totally stumped as to why this is a problem.
Any ideas?
EDIT: Here is the webpack config for the main repository
var webpackConfig = {
entry: {
app: './src/app/main.app.js',
vendor: ['angular']
},
output: {
path: DIST_DIRECTORY + '/scripts/',
publicPath: '/scripts/',
filename: '[name].min.js',
chunkFilename: '[name].min.js'
},
devtool: 'source-map',
module: {
loaders: [{
test: /\.js$/,
loader: 'babel'
}, {
test: /\.html$/,
loader: 'raw'
}]
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
unused: true,
dead_code: true
},
sourceMap: true
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.bundle.js")
],
devServer: {
contentBase: DIST_DIRECTORY + '/'
}
};

Related

Webpack works fine but webpack dev server does not run app gives console error

I am new to Vuejs Webpack configuration. I am trying to run vuejs app using dev server but unable to. Webpack command is running fine and I am able to build the app successfully and its running fine but when I am trying to run app with dev server its opening up the url on browser itself but throwing console error unable to trace whats going on.
const HtmlWebPackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const { VueLoaderPlugin } = require("vue-loader");
const path = require("path");
module.exports = {
entry: "./index.js",
output: {
path: path.resolve(__dirname, "./dist"),
filename: `js/[name]_[hash]_bundle.js`,
chunkFilename: `js/[name]_[chunkhash]_chunk.js`,
},
devServer: {
port: 4300,
},
module: {
rules: [
{
test: /\.vue$/,
loader: "vue-loader",
},
{
test: /\.js$/,
loader: "babel-loader",
},
{
test: /\.(css|scss)$/,
use: ["vue-style-loader", "css-loader", "sass-loader"],
},
],
},
optimization: {
splitChunks: { name: "vendor", chunks: "all" },
},
resolve: {},
plugins: [
new CleanWebpackPlugin(),
new VueLoaderPlugin(),
new HtmlWebPackPlugin({
template: "./index.html",
filename: "./index.html",
}),
],
devtool: "source-map",
};
This is the error I am getting while running webpack-dev-server command,
As you can see here its loading the js bundle files properly here in index.html

index.html disappears after watch triggered recompilation

I have a Chrome Extension where I started using webpack. I can build it just fine, but in development mode when I am run npm run watch after the first recompilation is triggered the index.html disappears from the build directory.
Here is script part of my package.json:
"build": "node utils/build.js",
"watch": "webpack --watch & webpack-dev-server --inline --progress --colors"
}
My webpack.config.js: (I have a bunch of content scripts listed as separate entry point as well that I omitted)
path = require("path"),
env = require("./utils/env"),
CleanWebpackPlugin = require("clean-webpack-plugin").CleanWebpackPlugin,
CopyWebpackPlugin = require("copy-webpack-plugin"),
HtmlWebpackPlugin = require("html-webpack-plugin"),
WriteFilePlugin = require("write-file-webpack-plugin"),
MiniCssExtractPlugin = require('mini-css-extract-plugin');
const fileExtensions = ["jpg", "jpeg", "png", "gif", "eot", "otf", "svg", "ttf", "woff", "woff2"];
const options = {
mode: process.env.NODE_ENV || "development",
entry: {
// the single js bundle used by the single page that is used for the popup, options and bookmarks
index: path.join(__dirname, "src", "", "index.js"),
// background scripts
"js/backgroundScripts/background": path.join(__dirname, "src", "js/backgroundScripts", "background.js"),
"js/backgroundScripts/messaging": path.join(__dirname, "src", "js/backgroundScripts", "messaging.js")
},
output: {
publicPath: '',
path: path.join(__dirname, "build"),
filename: "[name].bundle.js"
},
module: {
rules: [
{
enforce: "pre",
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
options: {
cache: true,
emitWarning: true
},
},
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: true,
},
},
'css-loader',
'sass-loader',
],
},
{
test: new RegExp('\.(' + fileExtensions.join('|') + ')$'),
loader: "file-loader?name=[name].[ext]",
exclude: /node_modules/
},
{
test: /\.html$/,
loader: "html-loader",
exclude: /node_modules/
},
{
test: /\.(js|jsx)$/,
loader: "babel-loader",
exclude: /node_modules/
},
]
},
resolve: {
modules: [path.resolve(__dirname, './src'), 'node_modules'],
extensions: fileExtensions.map(extension => ("." + extension)).concat([".jsx", ".js", ".css"])
},
plugins: [
// clean the build folder
new CleanWebpackPlugin(),
// expose and write the allowed env vars on the compiled bundle
new webpack.EnvironmentPlugin({
NODE_ENV: 'development', // use 'development' unless process.env.NODE_ENV is defined
DEBUG: false
}),
// copies assets that don't need bundling
new CopyWebpackPlugin([
"src/manifest.json",
{
from: "src/css",
to: 'css/'
},
{
from: "src/_locales",
to: '_locales/'
},
{
from: "src/images",
to: 'images/'
}
], { copyUnmodified: true }),
new HtmlWebpackPlugin({
template: path.join(__dirname, "src", "index.html"),
filename: "index.html",
chunks: ["index"]
}),
new WriteFilePlugin(),
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '[name].css',
chunkFilename: '[id].css',
}),
],
devServer: {
writeToDisk: true,
contentBase: path.join(__dirname, "../build")
}
};
if (env.NODE_ENV === "development") {
options.devtool = "cheap-module-source-map";
}
module.exports = options;
I can see index.html listed in the initial build log, but not any of the ones after that.
I would appreciate any clues of why this is is happening and how I could fix it. Thanks.
In the plugins section, you should put this line conditional only for production environment:
new CleanWebpackPlugin()
As it's role is to clean the build folder.

How can I make FontAwesome work with vue-cli webpack-simple template?

I generate a default project with vue-cli:
vue init webpack-simple grid-prototype
I install FontAwesome through npm:
npm install --save fontawesome
After that, I include it into main.js with:
import 'font-awesome/css/font-awesome.css'
I execute the app with:
npm run dev
And I get this error:
Failed to compile.
./node_modules/font-awesome/fonts/fontawesome-webfont.ttf?v=4.7.0
Module parse failed: Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
# ./node_modules/css-loader!./node_modules/font-awesome/css/font-awesome.css 7:684-735
# ./node_modules/font-awesome/css/font-awesome.css
# ./src/main.js
# multi (webpack)-dev-server/client?http://localhost:8082 webpack/hot/dev-server ./src/main.js
Here's my webpack.config.js (it's the default one created by the cli):
var path = require("path");
var webpack = require("webpack");
module.exports = {
entry: "./src/main.js",
output: {
path: path.resolve(__dirname, "./dist"),
publicPath: "/dist/",
filename: "build.js"
},
module: {
rules: [
{
test: /\.css$/,
use: ["vue-style-loader", "css-loader"]
},
{
test: /\.vue$/,
loader: "vue-loader",
options: {
loaders: {}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: "babel-loader",
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: "file-loader",
options: {
name: "[name].[ext]?[hash]"
}
}
]
},
resolve: {
alias: {
vue$: "vue/dist/vue.esm.js"
},
extensions: ["*", ".js", ".vue", ".json"]
},
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true
},
performance: {
hints: false
},
devtool: "#eval-source-map"
};
if (process.env.NODE_ENV === "production") {
module.exports.devtool = "#source-map";
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
]);
}
What am I doing wrong?
webpack-simple is suitable for quick prototyping and it doesn't have advanced rules.
Solution #1: Use webpack template instead of webpack-simple to avoid this and other issues in the future.
Solution #2: Use FontAwesome from CDN, for example:
https://www.bootstrapcdn.com/fontawesome/
I mean, just add the CDN css to your index.html
Solution #3: Add one more rule to your webpack config
module: {
rules: [
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
As it is in the webpack template:
https://github.com/vuejs-templates/webpack/blob/develop/template/build/webpack.base.conf.js

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.

Syntax error when testing React component Jasmine and Webpack

I keep getting an error when trying to run a simple test using React, Karma, Jasmine and Webpack. The error is ' Uncaught SyntaxError: Unexpected token < ', I think my jsx isn't being processed to js, but I don't know why that is happening as I understand webpack should handle that using the babel loader. If anyone can provide advice I would be grateful
Here are my files
karma.conf.js
var webpack = require("webpack"),
path = require("path");
// Karma configuration
module.exports = function(config) {
config.set({
basePath: "",
frameworks: ["jasmine"],
files: [
"../test/!**!/!*.test.js"
],
preprocessors: {
"./test/!**!/!*.test.js": ["webpack"]
},
webpack: {
module: {
loaders: [
{
test: /\.jsx?$/i,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-1']
}
},
{ test: /\.less$/, loader: "style!css!less" }
]
},
},
plugins: [
new webpack.ResolverPlugin([
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
])
],
resolve: {
root: __dirname,
extensions: [
'',
'.json',
'.js',
'.jsx'
]
}
},
webpackMiddleware: {
noInfo: true
},
plugins: [
require("karma-webpack"),
require("karma-jasmine"),
require("karma-chrome-launcher")
],
reporters: ["dots"],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ["Chrome"],
singleRun: false
});
};
my test file example.test.js
var Comp = require('../../../js/common/components/MyComp.jsx'),
React = require('react'),
TestUtils = React.addons.TestUtils;
describe("Component Test", function() {
it("renders an h1", function () {
var component = TestUtils.renderIntoDocument(
<Comp/> // syntax error here
);
var h2 = TestUtils.findRenderedDOMComponentWithTag(
component, 'h2'
);
expect(h1).toExist();
});
});
So the syntax error happens at < Comp... . Thanks!
Apologise it was an error in setting the correct path to the test file.
files: [
"../test/**/*.test.js"
],
preprocessors: {
"../test/**/*.test.js": ["webpack"]
},