Webpack Dynamic Config Loading Fails - javascript

I was following instructions to import config dynamically based on an environment variable using webpack. This is according to official documentation:
https://webpack.js.org/plugins/normal-module-replacement-plugin/
Example:
File: package.json
{
"name": "03_branching",
"version": "1.0.0",
"description": "",
"main": "",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"develop": "webpack --mode development --watch",
"build": "webpack --mode production"
},
"author": "",
"license": "ISC",
"dependencies": {
"string-replace-loader": "^2.1.1",
"webpack": "~4.6.0"
},
"devDependencies": {
"webpack-cli": "^2.0.15"
}
}
Example:
File: configLoader.js
const fs = require('fs');
console.log('fs', fs);
const config = fs.readFileSync("./config/APP_ENV.json");
const properties = JSON.parse(config);
console.log("Environment: " + properties.environment);
console.log("HomepageUrl: " + properties.homepageUrl);
File: webpack.config.js
"use strict";
const webpack = require('webpack');
const path = require('path');
module.exports = function(env) {
console.log('NODE_ENV: ', env.NODE_ENV); // 'local'
let newEnv = 'local';
if (env.NODE_ENV !== undefined) {
newEnv = env.NODE_ENV;
}
console.log('newEnv', newEnv);
return {
target: 'web',
node: {
fs: 'empty'
},
entry: path.join(__dirname, "./", "configLoader.js"),
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
libraryTarget: 'var',
library: 'EntryPoint'
},
module: {
rules: [
{
test: /configLoader\.js$/,
loader: 'string-replace-loader',
options: {
search: 'APP_ENV',
replace: `${newEnv}`,
flags: 'i'
}
}
]
}
}
};
File: config/local.json
{
"environment": "local",
"homepageUrl": "http://localhost:8080"
}
File: config/production.json
{
"environment": "production",
"homepageUrl": "http://www.google.com"
}
I try and run node dist/bundle.js but I get the following error...
➜ 03_branching git:(master) ✗ node dist/bundle.js fs {} /Users/jamesmurphy/Development/Repos/clients/PacktPublishing/NodeJsDesignPatterns/Chapter08/exercises/03_branching/dist/bundle.js:1
(function (exports, require, module, __filename, __dirname) { var EntryPoint=function(n){var e={};function o(r){if(e[r])return e[r].exports;var t=e[r]={i:r,l:!1,exports:{}};return n[r].call(t.exports,t,t.exports,o),t.l=!0,t.exports}return o.m=n,o.c=e,o.d=function(n,e,r){o.o(n,e)||Object.defineProperty(n,e,{configurable:!1,enumerable:!0,get:r})},o.r=function(n){Object.defineProperty(n,"__esModule",{value:!0})},o.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return o.d(e,"a",e),e},o.o=function(n,e){return Object.prototype.hasOwnProperty.call(n,e)},o.p="",o(o.s=1)}([function(n,e){},function(n,e,o){const r=o(0);console.log("fs",r);const t=r.readFileSync("./config/production.json"),c=JSON.parse(t);console.log("Environment: "+c.environment),console.log("HomepageUrl: "+c.homepageUrl)}]);
TypeError: r.readFileSync is not a function
at Object.<anonymous> (/Users/jamesmurphy/Development/Repos/clients/PacktPublishing/NodeJsDesignPatterns/Chapter08/exercises/03_branching/dist/bundle.js:1:686)
at o (/Users/jamesmurphy/Development/Repos/clients/PacktPublishing/NodeJsDesignPatterns/Chapter08/exercises/03_branching/dist/bundle.js:1:186)
at /Users/jamesmurphy/Development/Repos/clients/PacktPublishing/NodeJsDesignPatterns/Chapter08/exercises/03_branching/dist/bundle.js:1:600
at Object.<anonymous> (/Users/jamesmurphy/Development/Repos/clients/PacktPublishing/NodeJsDesignPatterns/Chapter08/exercises/03_branching/dist/bundle.js:1:609)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
It works if I run
node configLoader.js
But if I run the webpack command:
webpack --env.NODE_ENV=production
node dist/bundle.js
It fails... How do you bundle all of the node core modules here using webpack? I'm using webpack version 4.6.0
Cheers!

You are using the wrong target.
readFileSync only exists in node. But you are compiling for web.
If you change your target to node, everything should work.
I suspect you don't want to load the config file on runtime, but compile different option depending on the environment?
If so, take a look at webpack-define-plugin. You can put your config in a variable without loading a file on runtime.
This will then also work in the browser.

Related

Both Require and import not working javascript

I am trying to create a cli tool to make a todo list. For some reason I can't figure out I'm unable to use either require or import when trying to import the Chalk package for highlighting terminal outputs
here is what I have for my index.js file
#! /usr/bin/env node
const { program } = require("commander");
const list = require("./commands/list.js");
program.command("list").description("List all the TODO tasks").action(list);
program.parse();
Here is my list.js file
#! /usr/bin/env node
const conf = new (require("conf"))();
const chalk = require("chalk");
function list() {
const todoList = conf.get("todo-list");
if (todoList && todoList.length) {
console.log(
chalk.blue.bold(
"Tasks in green are done. Tasks in yellow are still not done."
)
);
todoList.forEach((task, index) => {
if (task.done) {
console.log(chalk.greenBright(`${index}. ${task.text}`));
} else {
console.log(chalk.yellowBright(`${index}. ${task.text}`));
}
});
} else {
console.log(chalk.red.bold("You don't have any tasks yet."));
}
}
module.exports = list;
and my package.json file
{
"name": "near-clear-state",
"version": "1.0.0",
"description": "Tool to let NEAR users clear the state of their account ",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"type": "commonjs",
"author": "Dorian",
"license": "ISC",
"dependencies": {
"chalk": "^5.0.0",
"commander": "^8.3.0",
"conf": "^10.1.1",
"near-api-js": "^0.44.2"
},
"bin": {
"near-clear-state": "./index.js"
}
}
when I try running anything from this cli tool I'm making I get this error if I use require
➜ near-clear-state near-clear-state --help
/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js:4
const chalk = require("chalk");
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/node_modules/chalk/source/index.js from /Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js not supported.
Instead change the require of index.js in /Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js:4:15)
at Object.<anonymous> (/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/index.js:3:14) {
code: 'ERR_REQUIRE_ESM'
}
Or this error when i use import
/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js:3
import { Chalk } from "chalk";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1026:15)
at Module._compile (node:internal/modules/cjs/loader:1061:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/index.js:3:14)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
Node.js v17.4.0
Please help me
Use the import syntax, and add "type": "module" into your package.json to allow for ES6 imports.

Getting 'ReferenceError: document is not defined' only when I run webpack --watch?

Why would document stop being defined only when I run webpack --watch? When I run my build or dev script, compiling works great. It's only when I try and watch. New to WP.
My end goal here is to polyfill my client-side JS and auto-reload the browser window that LiveServer opens (VSCode plugin). Right now, I'm just trying to automatically compile my code after making changes which will trigger LiveServer to reload. Is there a better approach to this?
index.js
const errors = document.querySelector('.errors');
webpack.config.js
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const NodemonPlugin = require('nodemon-webpack-plugin');
const config = {
watch: true,
entry: {
rater_stater: "./src/index.js",
},
output: {
filename: "index.js",
path: path.resolve(__dirname, "dist"),
},
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
MiniCssExtractPlugin.loader,
// Translates CSS into CommonJS
"css-loader",
// Compiles Sass to CSS
"sass-loader",
"postcss-loader",
],
},
],
},
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "style.css",
chunkFilename: "style-[id].css",
}),
new NodemonPlugin({
env: {
NODE_ENV: 'development',
},
})
],
};
module.exports = (env, argv) => {
if (argv.mode === "development") {
config.devtool = "source-map";
}
if (argv.mode === "production") {
config.module.rules.push({
test: /\.js?$/,
use: [
{
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"],
},
},
],
exclude: /node_modules/,
});
}
return config;
};
package.json
"scripts": {
"build": "webpack --mode=production",
"dev": "webpack --mode=development",
"watch": "webpack --watch"
},
error
ReferenceError: document is not defined
at /Users/brad/Documents/vscode/rater-stater/dist/index.js:1:180375
at /Users/brad/Documents/vscode/rater-stater/dist/index.js:1:180732
at Object.<anonymous> (/Users/brad/Documents/vscode/rater-stater/dist/index.js:1:180735)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...
Edit:
I'm also getting this error when it does compile with webpack --mode=development. It's like my variables are all set to null? I'm so confused. Why would this happen? I've tried changing it from var to let to const and still get the same error.
Edit 2:
Ran a couple more tests. It's like everything related to document is broken.. but I can console.log document. I just can't use querySelector, etc.
All of these issues stopped when I wrapped my code with
document.addEventListener("DOMContentLoaded", function() {
...code
}
🤦

Webpack Build SyntaxError: Unexpected token )

Note: I read through the other similar questions (here and others), but they are all about earlier versions of webpack and babel and do not solve the following issue.
This is serving just fine, but when I run npm run build I'm getting the following error. How do I solve this? (And how do I get better errors than this?, the log is just as bad).
> react_01#1.0.0 build /Users/monkeydo/Documents/code/__tests/react_01
> webpack --mode production
/Users/monkeydo/Documents/code/__tests/react_01/node_modules/webpack-cli/bin/cli.js:41
)} manually.`,
^
SyntaxError: Unexpected token )
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:549:28)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at runCli (/Users/monkeydo/Documents/code/__tests/react_01/node_modules/webpack/bin/webpack.js:69:2)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! react_01#1.0.0 build: `webpack --mode production`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the react_01#1.0.0 build script.
My webpack file looks like this:
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
//entry: ['#babel/polyfill', './src/index.js'],
entry: './src/index.js',
// Where files should be sent once they are bundled
output: {
path: path.join(__dirname, '/dist'),
filename: 'index.bundle.js'
},
// webpack 5 comes with devServer which loads in development mode
devServer: {
port: 3000,
watchContentBase: true
},
// Rules of how webpack will take our files, complie & bundle them for the browser
module: {
rules: [
{
test: /\.(js|jsx)$/,
// test: /\.jsx?/,
exclude: /nodeModules/,
use: {
loader: 'babel-loader',
query:
{
presets:['react', 'preset-env']
}
}
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader']
}
]
},
plugins: [new HtmlWebpackPlugin({ template: './src/index.html' }), new MiniCssExtractPlugin()]
}
My package json looks like this:
{
"name": "react_01",
"version": "1.0.0",
"description": "",
"main": "index.jsx",
"scripts": {
"serve": "webpack serve --mode development",
"build": "webpack --mode production"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.14.6",
"#babel/preset-env": "^7.14.7",
"#babel/preset-react": "^7.14.5",
"babel-loader": "^8.2.2",
"css-loader": "^6.0.0",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.3.2",
"mini-css-extract-plugin": "^2.1.0",
"style-loader": "^3.1.0",
"webpack": "^5.45.1",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2"
}
My babelrc file looks like this:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
My index.js file looks like this:
import React from "react"
import ReactDom from "react-dom"
import App from "./components/app"
import "./style.css"
ReactDom.render(<App />, document.getElementById('app'))
My app.js file looks like this:
import React from "react"
function App() {
return (<div>
<h2>Welcome to My new React App</h2>
<h3>Date : {new Date().toDateString()}</h3>
</div>)
}
export default App
*** Edit: not sure what I was thinking... I totally forgot to add the webpack code before :o ! I guess that was a dyslexic senior moment. It's added now.
Just remove the styles import
import "./style.css"
Webpack speaks JavaScript, not css, if you want it to learn it you need to create a webpack config file and use the proper loader to handle css

Build error occurred ReferenceError: describe is not defined > During now.sh deployment

I'm using now.sh to deploy my nextjs (React) app. And the build is failing due to this error:
Build error occurred
ReferenceError: describe is not defined
Not sure why this started happening, here is my .babelrc
{
"env": {
"development": {
"compact": false,
"presets": [
"next/babel",
"#zeit/next-typescript/babel"
],
"plugins": [
["styled-components", {"ssr": true, "displayName": true}],
["#babel/plugin-proposal-decorators", {"legacy": true}]
]
},
"production": {
"presets": [
"next/babel",
"#zeit/next-typescript/babel"
],
"plugins": [
["styled-components", {"ssr": true, "displayName": true}],
["#babel/plugin-proposal-decorators", {"legacy": true}]
]
},
"test": {
"compact": false,
"presets": [
"#babel/preset-typescript",
["next/babel", {"preset-env": { "modules": "commonjs" }}]
],
"plugins": [
["styled-components", { "ssr": true, "displayName": true }],
["#babel/plugin-proposal-decorators", { "legacy": true }],
["babel-plugin-sass-vars"]
]
}
}
}
package.json
"engines" : {
"node" : ">=8.10.0 <11.0.0"
},
"scripts": {
"dev": "NODE_ENV=development next -p 7777",
"build": "NODE_ENV=production next build",
"start": "next -p 7777",
"test": "NODE_ENV=test jest --no-cache",
"test-watch": "NODE_ENV=test jest --watch --no-cache",
"coverage": "NODE_ENV=test jest --coverage",
"update-snap": "NODE_ENV=test jest --updateSnapshot"
},
Full log:
running "npm run now-build"
> moon.holdings#2.0.0 now-build /tmp/7418164
> next build
Creating an optimized production build ...
> Using external babel configuration
> Location: "/tmp/7418164/.babelrc"
> Build error occurred
ReferenceError: describe is not defined
at Module.kAI8 (/tmp/7418164/.next/serverless/pages/__tests__/about.test.js:63996:1)
at __webpack_require__ (/tmp/7418164/.next/serverless/pages/__tests__/about.test.js:23:31)
at module.exports.+3sd.exports.__esModule (/tmp/7418164/.next/serverless/pages/__tests__/about.test.js:91:18)
at Object.<anonymous> (/tmp/7418164/.next/serverless/pages/__tests__/about.test.js:94:10)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
npm
ERR! code ELIFECYCLE
The first test where the describe is used:
import React from 'react'
import { shallow } from 'enzyme'
import toJson from 'enzyme-to-json'
import About from '../about.tsx'
describe('<About /> component', () => {
describe('rendering', () => {
const wrapper = shallow(<About />);
it('should render a component matching the snapshot', () => {
const tree = toJson(wrapper);
expect(tree).toMatchSnapshot();
expect(wrapper).toHaveLength(1);
expect(wrapper.contains(<About/>));
});
});
});
next.config
module.exports = (phase, { defaultConfig }) => {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
module: {
loaders: [
{
test: /\.json$/,
loader: 'json-loader'
}
]
}
// Note: Nextjs provides webpack above so you should not `require` it
// Perform customizations to webpack config
// Important: return the modified config
config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
return config
}
// ✅ Put the require call here.
const withTypescript = require('#zeit/next-typescript')
const withCSS = require('#zeit/next-sass')
// withCSS({target: 'serverless'})
return withTypescript(withCSS({
webpack(config, options) {
return config
}
}))
}
I removed the tests that covered the /pages directory. NextJS used pages for routing. Not sure why that was causing the problem, ran coverage and looks like pages wasn't necessary to cover.
Hoping for a better answer from someone at the NextJS / Now.sh team, and I'll select that.
Easy fix: https://github.com/zeit/next.js/issues/3728#issuecomment-523789071
pageExtensions: ['page.tsx']
An option that allows the tests inside pages folder:
change webpack settings direct in next.config.js
module.exports = {
webpack: (config, { webpack }) => {
config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
return config
}
}
It is ignoring whatever __tests__ folder found on the build process.
If you are looking to colocate non-page files with pages in the /pages directory, you can use Custom Page Extensions to force your pages to have a file extension of .page.js. Once that is setup, Next.js will ignore any files that don't have .page in the file extension.
next.config.js
module.exports = {
// Force .page prefix on page files (ex. index.page.tsx) so generated files can be included in /pages directory without Next.js throwing build errors
pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js'],
}
I wrote some docs for this use case that have yet to be merged https://github.com/vercel/next.js/pull/22740. The docs link above now contains these changes.
The original Github issue where this was discovered is https://github.com/vercel/next.js/issues/3728#issuecomment-895568757.

Webpack: ERROR in ./~/sqlite3/~/node-pre-gyp/lib/node-pre-gyp.js Module not found: Error: Cannot resolve 'file' or 'directory' ../package

I want to use Webpack on my projects, but when I run
npm run dev
, I get this error.
ERROR in ./~/sqlite3/~/node-pre-gyp/lib/node-pre-gyp.js Module not
found: Error: Cannot resolve 'file' or 'directory' ../package in
/Users/caizongming/Flowerhop/-DBLab-Alarm-Project-/Server/node_modules/sqlite3/node_modules/node-pre-gyp/lib
# ./~/sqlite3/~/node-pre-gyp/lib/node-pre-gyp.js 60:16-37
ERROR in ./~/sqlite3/~/node-pre-gyp/lib/info.js Module not found:
Error: Cannot resolve module 'aws-sdk' in
/Users/caizongming/Flowerhop/-DBLab-Alarm-Project-/Server/node_modules/sqlite3/node_modules/node-pre-gyp/lib
# ./~/sqlite3/~/node-pre-gyp/lib/info.js 14:14-32
ERROR in ./~/sqlite3/~/node-pre-gyp/lib/publish.js Module not found:
Error: Cannot resolve module 'aws-sdk' in
/Users/caizongming/Flowerhop/-DBLab-Alarm-Project-/Server/node_modules/sqlite3/node_modules/node-pre-gyp/lib
# ./~/sqlite3/~/node-pre-gyp/lib/publish.js 17:14-32
ERROR in ./~/sqlite3/~/node-pre-gyp/lib/unpublish.js Module not found:
Error: Cannot resolve module 'aws-sdk' in
/Users/caizongming/Flowerhop/-DBLab-Alarm-Project-/Server/node_modules/sqlite3/node_modules/node-pre-gyp/lib
# ./~/sqlite3/~/node-pre-gyp/lib/unpublish.js 15:14-32
ERROR in ./~/sqlite3/~/rc/index.js Module build failed: Error: Parse
Error: Line 1: Unexpected token ILLEGAL
at throwError (/Users/caizongming/Flowerhop/-DBLab-Alarm-Project-/Server/node_modules/jsx-loader/node_modules/jstransform/node_modules/esprima-fb/esprima.js:2823:21)
at scanPunctuator (/Users/caizongming/Flowerhop/-DBLab-Alarm-Project-/Server/node_modules/jsx-loader/node_modules/jstransform/node_modules/esprima-fb/esprima.js:1011:9)
at advance (/Users/caizongming/Flowerhop/-DBLab-Alarm-Project-/Server/node_modules/jsx-loader/node_modules/jstransform/node_modules/esprima-fb/esprima.js:1747:16)
at peek (/Users/caizongming/Flowerhop/-DBLab-Alarm-Project-/Server/node_modules/jsx-loader/node_modules/jstransform/node_modules/esprima-fb/esprima.js:1773:21)
at parseProgram (/Users/caizongming/Flowerhop/-DBLab-Alarm-Project-/Server/node_modules/jsx-loader/node_modules/jstransform/node_modules/esprima-fb/esprima.js:6535:9)
at Object.parse (/Users/caizongming/Flowerhop/-DBLab-Alarm-Project-/Server/node_modules/jsx-loader/node_modules/jstransform/node_modules/esprima-fb/esprima.js:7713:23)
at getAstForSource (/Users/caizongming/Flowerhop/-DBLab-Alarm-Project-/Server/node_modules/jsx-loader/node_modules/jstransform/src/jstransform.js:244:21)
at Object.transform (/Users/caizongming/Flowerhop/-DBLab-Alarm-Project-/Server/node_modules/jsx-loader/node_modules/jstransform/src/jstransform.js:267:11)
at Object.transform (/Users/caizongming/Flowerhop/-DBLab-Alarm-Project-/Server/node_modules/jsx-loader/node_modules/jstransform/src/simple.js:105:28)
at Object.module.exports (/Users/caizongming/Flowerhop/-DBLab-Alarm-Project-/Server/node_modules/jsx-loader/index.js:15:31)
# ./~/sqlite3/~/node-pre-gyp/lib/info.js 11:13-26
This is my WEBPACK.CONFIG.js
var path = require ('path');
module.exports = {
entry: './server.js',
output: {
filename: 'bundle.js'
},
module: {
loaders:[
{ test: /\.css$/, loader: "style!css" },
{ test: /\.js$/, loader: 'jsx-loader?harmony' },
{ test: /\.json$/, loader: 'json-loader' }
]
},
resolve: {
fallback: path.join(__dirname, "node_modules"),
extensions : ['', '.js', '.jsx']
},
resolveLoader: { fallback: path.join(__dirname, "node_modules") },
target: 'node'
};
This is package.json.
{
"name": "biocenter",
"version": "1.0.0",
"description": "",
"main": "server.js",
"directories": {
"test": "test"
},
"dependencies": {
"body-parser": "^1.15.0",
"express": "^4.13.4",
"request": "^2.72.0",
"sqlite3": "^3.1.4",
"querystring": "^0.2.0",
"should": "^8.3.2"
},
"devDependencies": {
"brfs": "^1.4.3",
"json-loader": "^0.5.4",
"mocha": "^2.4.5",
"transform-loader": "^0.2.3",
"webpack": "^1.13.1"
},
"scripts": {
"test": "mocha",
"start": "node server.js",
"dev": "webpack-dev-server --devtool eval --progress --colors",
"deploy": "NODE_ENV=production webpack -p"
},
"repository": {
"type": "git",
"url": "git+https://github.com/FlowerHop/-DBLab-Alarm-Project-.git"
},
"author": "Flowerhop",
"license": "ISC",
"bugs": {
"url": "https://github.com/FlowerHop/-DBLab-Alarm-Project-/issues"
},
"homepage": "https://github.com/FlowerHop/-DBLab-Alarm-Project-#readme"
}
Can anybody help me fix this problem?
I encountered the similar problem with the lzma-native, which also uses node-pre-gyp. The problem is they all directly require the node-pre-gyp in the module. I try to replace the line of code that use node-pre-gyp
var nodePreGyp = require('node-pre-gyp');
var path = require('path');
var binding_path = nodePreGyp.find(path.resolve(path.join(__dirname,'./package.json')));
var native = require(binding_path);
into
var native = require('pre-gyp-find')('lzma_native');
// notice that the parameter here is the binary module name in package.json of lzma-native
And that finally works for me. Though, this solution requires us to modify the source code, and add an additional dependency 'pre-gyp-find'. Maybe you could send a PR to author about this.
This is not the best solution, since it doesn't actually solve but avoid the problem.
I noticed everything seems right during npm install, but actually there is some error during install. My problem was fixed with npm install sqlite3 --build-from-source.

Categories